Can';t使用subprocess.Popen打印bash输出
尝试使用subprocess.Popen时,我无法获取bash输出并收到以下错误: SyntaxError:无效语法 代码是:Can';t使用subprocess.Popen打印bash输出,bash,python-2.7,subprocess,Bash,Python 2.7,Subprocess,尝试使用subprocess.Popen时,我无法获取bash输出并收到以下错误: SyntaxError:无效语法 代码是: 导入子流程 #图形卡 out=subprocess.Popen(['lspci','|','grep','NVIDIA'], stdout=子流程.PIPE, stderr=subprocess.STDOUT) stdout,stderr=out.communicate() 打印(标准输出) |不是命令参数;它是连接两个命令的shell语法。对于此命令,您需要让shel
导入子流程
#图形卡
out=subprocess.Popen(['lspci','|','grep','NVIDIA'],
stdout=子流程.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr=out.communicate()
打印(标准输出)
|
不是命令参数;它是连接两个命令的shell语法。对于此命令,您需要让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)
应该有一个写入到stderr的错误(来自
lspci
,表明它无法识别以|
、grep
和NVIDIA
作为参数进行调用,原因在chepner的回答中给出)。你好,朋友。那很好用。非常感谢您的帮助和解释!