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

标签 python unix

我有以下内容:

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 安装(没有额外的模块)来实现这一点

最佳答案

您需要为每个原始命令调用一次 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

subprocess documentation进行了深入的讨论。

关于python - 在 python 中运行 shell 命令并读取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24778630/

相关文章:

perl - 查找列中的唯一值并将唯一值替换为数字

python - Scrapy:创建爬行索引页面并保存每个对应链接的整个 HTML 页面的 Spider

python - K 最短路径 Python 不工作

unix - 无法进入系统调用源代码

c++ - 如何判断 stderr 是否将输出定向到文件?

Bash 脚本 if 语句

c - 阻止来自多个套接字的 select()

python - 当我在包含字典的列表中进行枚举时,出现列表索引超出范围错误

c++ - Python C API - 创建关键字

python - 如何在 Django 1.9 中显示用户状态(在线、离线)?