python子进程运行shell与gawk正则表达式不起作用

时间:2016-01-27 08:48:47

标签: python subprocess gawk

bash cmd是:

 ps aux |grep tomcat  |grep -Ev grep |grep -o 'Dcatalina.base=.*tomcat' |gawk -F'[ =]+' '{print $2}'"

这适用于bash,输出为:

/opt/Backuplog/tomcat-6.0.44

但是,我想在python中使用这个cmd,所以我使用子进程

out=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output,outerr = out.communicate()

但是输出是'',我想知道如何处理它

1 个答案:

答案 0 :(得分:0)

使用bash运行它,您的命令应该是:

cmd = '''bash -i -c "ps aux |grep tomcat  |grep -Ev grep |grep -o 'Dcatalina.base=.*tomcat' |gawk -F'[ =]+' '{print $2}'"'''

或者您可以使用subprocess.check_output

cmd = "ps aux |grep tomcat  |grep -Ev grep |grep -o 'Dcatalina.base=.*tomcat' |gawk -F'[ =]+' '{print $2}'"

subprocess.check_output(['bash', '-i', '-c', cmd])