根据提供的答案here,我想将错误保存为字符串:
p = subprocess.Popen(['ding', 'dong'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output, errors = p.communicate()
但是,似乎重定向stderr不起作用:
>>> p = subprocess.Popen(['ding', 'dong'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 993, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
将错误捕获为字符串的正确方法是什么?
答案 0 :(得分:2)
问题中的错误消息不是来自子进程。它是在子进程执行之前生成的。您无法使用stderr
选项捕获该错误。
确保路径中有ding
个程序。