如何运行"ps cax |grep 某事在 Python 中?

2022-01-23 00:00:00 python command pipe

问题描述

如何运行带有管道 | 的命令?

子进程模块看起来很复杂...

有没有类似的

输出,错误 = `ps cax |grep 某事`

在 shell 脚本中?

解决方案

参见 更换shell管道:

导入子流程proc1 = subprocess.Popen(['ps', 'cax'], stdout=subprocess.PIPE)proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout,标准输出=子进程.PIPE,标准错误=子进程.PIPE)proc1.stdout.close() # 如果 proc2 退出,则允许 proc1 接收 SIGPIPE.出来,错误 = proc2.communicate()print('out: {0}'.format(out))print('err: {0}'.format(err))

PS.使用 shell=True 可能很危险.例如,请参阅文档中的 警告.p><小时>

还有 sh 模块,它可以使 Python 中的子进程脚本编写更加愉快:

导入 sh打印(sh.grep(sh.ps(cax"),某事"))

How do I run a command with a pipe | in it?

The subprocess module seems complex...

Is there something like

output,error = `ps cax | grep something`

as in shell script?

解决方案

See Replacing shell pipeline:

import subprocess

proc1 = subprocess.Popen(['ps', 'cax'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)

proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))
print('err: {0}'.format(err))

PS. Using shell=True can be dangerous. See for example the warning in the docs.


There is also the sh module which can make subprocess scripting in Python a lot more pleasant:

import sh
print(sh.grep(sh.ps("cax"), 'something'))

相关文章