【发布时间】:2018-01-15 03:55:18
【问题描述】:
我一直在用 subprocess 模块测试标准错误。如果我用 linux shell 命令ls 写一个简单的 shell=True 测试,故意输入错误:
p=subprocess.Popen(["lr"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
out, err=p.communicate()
print ("standard error")
print(err)
它从 shell 输出通常的:lr: command not found。
但是如果shell=False,我不太明白为什么程序执行会出错
Traceback (most recent call last):
File "importInteresantes.py", line 6, in <module>
p=subprocess.Popen(["lr"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
File "/usr/lib/python2.7/subprocess.py", line 390, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1024, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我认为它会给我相同的输出。代码是错误的还是我应该获得相同的标准错误的观点?
注意:以防万一我也尝试过使用 python3
【问题讨论】:
-
用于启动命令的机制在这两种情况下非常不同。为什么您期望错误诊断完全相同?
-
"lr: command not found" 是一个 shell 错误消息。如果你不使用 shell,那么你就没有 shell 来为你显示 shell 错误消息。
-
但我希望程序至少运行,然后弹出一些错误。并不是说它根本无法运行。所以你不知道我用python输入错误命令的情况吗?我还听说使用
shell=True可能会有风险
标签: python subprocess stderr