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 中?


基础教程推荐
猜你喜欢
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01