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


要将管道与子进程模块一起使用,必须传递shell=True。

然而,出于各种原因,这确实是不可取的,尤其是安全性。相反,分别创建ps和grep进程,并将输出从一个管道到另一个,如下所示:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

然而,在您的特定情况下,简单的解决方案是调用子进程。check_output(('ps', '-A')),然后输出str.find。

或者始终可以在子进程对象上使用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方法返回一个由标准输出和标准错误组成的元组。

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

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

此外,尝试使用'pgrep'命令而不是'ps -A | grep' 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])

使用来自subprocess.run的输入,您可以将一个命令的输出传递给第二个命令。

import subprocess
    
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
                              input=ps.stdout, capture_output=True)
print(processNames.stdout.decode('utf-8').strip())