无法使用subprocess.Popen打印bash输出

时间:2019-08-11 12:45:57

标签: bash python-2.7 subprocess

当尝试使用subprocess.Popen时,我无法获得bash输出并收到以下错误:

SyntaxError:语法无效

代码是:

import subprocess

# Graphic-card

out = subprocess.Popen(['lspci', '|', 'grep', ''NVIDIA'''],

         stdout=subprocess.PIPE,

         stderr=subprocess.STDOUT)

stdout,stderr = out.communicate()

print(stdout)

1 个答案:

答案 0 :(得分:2)

|不是命令参数;它是连接两个命令的shell语法。对于此命令,您需要让外壳处理管道:

out = subprocess.Popen("lspci | grep NVIDIA", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

或创建两个Popen实例并自己连接它们:

pre_out = subprocess.Popen(["lspci"], stdout=subprocess.PIPE)
out = subprocess.Popen(["grep", "NVIDIA"], stdin=pre_out.stdout, stderr=subprocess.STDOUT)