How to run quot; ps cax | grep something quot; in Python?(如何运行ps cax |grep 某事在 Python 中?)
本文介绍了如何运行"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 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何运行"ps cax |grep 某事在 Python 中?


猜你喜欢
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01