我想使用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方法返回一个由标准输出和标准错误组成的元组。
请参阅使用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())
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 在Bash中检查变量是否存在于列表中
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出