当尝试使用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)
答案 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)