我想使用subprocess.check_output() ps -A | grep 'process_name'。 我尝试了各种解决方案,但到目前为止都没用。有人能指导我怎么做吗?


当前回答

command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

其他回答

此外,尝试使用'pgrep'命令而不是'ps -A | grep' process_name'

你可以尝试sh.py中的管道功能:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

请参阅使用subprocess设置管道的文档:http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

我还没有测试下面的代码示例,但它应该是你想要的:

query = "process_name"
ps_process = Popen(["ps", "-A"], stdout=PIPE)
grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep_process exits.
output = grep_process.communicate()[0]
command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

或者始终可以在子进程对象上使用communication方法。

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

communication方法返回一个由标准输出和标准错误组成的元组。