如何运行"ps cax |grep 某事在 Python 中? [英] How to run " ps cax | grep something " in Python?

查看:28
本文介绍了如何运行"ps cax |grep 某事在 Python 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有没有类似的

输出,错误 = `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'))

这篇关于如何运行"ps cax |grep 某事在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆