在python中运行shell命令并读取输出

猎豹

我有以下内容:

cmd = "ps aux | grep 'java -jar' | grep -v grep | awk '//{print $2}'".split(' ')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out

当我在控制台中(在python之外)运行命令时,我得到了所需的输出。在python中运行以上代码会打印出空白行。我假设cmd(特别是|运算符)有问题,但是我不确定。

我需要通过标准的Python 2.6.6安装来实现这一点(无需其他模块)

罗伯托·雷亚莱(Roberto Reale)

您需要Popen()对每个原始命令(通过管道连接)使用一次调用,如下所示:

import subprocess

p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "java -jar"], stdin=p1.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p3 = subprocess.Popen(["grep", "-v", "grep"], stdin=p2.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
p4 = subprocess.Popen(["awk", "//{print $2}"], stdin=p3.stdout, stdout=subprocess.PIPE,  stderr=subprocess.PIPE)
out, err = p4.communicate()

print out

子文档有一个深入的讨论。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从shell命令输出中读取python

在Python中运行Shell命令

如何读取shell命令的输出

获取Python(cron)中Shell命令的输出?

运行shell命令并捕获输出

Python在shell中运行多行命令

在Python中运行shell内置命令

如何在python中运行shell命令

Shell脚本:从命令输出读取输入

在shell中运行vscode命令与输出中显示的命令有什么区别?

运行python文件并读取输出

python中的Google电子表格读取脚本不是从cron计划运行,但在我运行它时可以运行shell命令

运行shell命令的水晶语言并捕获输出

如何根据shell脚本中另一个命令的输出运行命令?

在go中运行带有“从子shell重定向输出”语句的shell命令

在终端中运行命令的输出

如何在shell脚本中逐行读取多行输出命令行?

执行Shell命令,并在Chrome打包的应用中读取其输出

在Elixir中运行Shell命令

在Swift中运行Shell命令

在Python子进程中运行连续的Shell命令

在Python3中运行Linux Shell命令

在Linux Shell脚本中并行运行python命令

如何在Gnuplot中运行Shell命令并将输出放置在新文件中

谁可以在 Centos X64 中运行 shell (.sh) 脚本并读取输出?

将 bash shell 脚本的输出作为 shell 命令运行?

如何通过 Python 运行两个 adb shell 命令,但只存储一个输出?

使用asyncio(Python 3.4+)异步接收长时间运行的shell命令的输出?

如何在Unix Shell中运行命令,然后从/返回Java应用程序的输出