从 python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) 捕获 stderr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/914320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
提问by Patrick Wolf
I have seen this posted so many times here; yet failed to capture intentional errors from command. Best partial work I have found so far..
我在这里多次看到这个帖子;但未能从命令中捕获故意错误。迄今为止我发现的最好的部分工作..
from Tkinter import *
import os
import Image, ImageTk
import subprocess as sub
p = sub.Popen('datdsade',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output+ "Error: " + errors )
root.mainloop()
回答by Patrick Wolf
This works perfectly for me:
这对我来说非常有效:
import subprocess
try:
#prints results
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex:
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output
回答by SpliFF
Are you 100% sure 'datdsade' actually writes to stderr? If so then possibly it's buffering its stderr, or blocking on it.
您是否 100% 确定 'datdsade' 确实写入了 stderr?如果是这样,那么它可能正在缓冲它的 stderr,或者阻塞它。
EDIT: I'd suggest running 'datdsade' (your program) in bash (assuming you have linux, you can dl sh.exe for windows) and seeing if you can capture your stderr to a file datdsade 2> errors.txt. Be aware that if you are on Windows stderr will not output in a DOS window. You may have more luck writing to a log file first and reading it back or having python store it in a variable.
编辑:我建议在 bash 中运行“datdsade”(你的程序)(假设你有 linux,你可以 dl sh.exe for windows)并查看你是否可以将你的 stderr 捕获到文件 datdsade 2> errors.txt。请注意,如果您使用的是 Windows,stderr 将不会在 DOS 窗口中输出。您可能会更幸运地先写入日志文件,然后再将其读回或让 Python 将其存储在变量中。
Alternatively stderr=sub.STDOUT will merge your errors with the stdout.
或者 stderr=sub.STDOUT 会将您的错误与标准输出合并。
EDIT AGAIN: Ignore the above, since communicate() is capturing all of this. I would say the problem is definately that program you chose never writes to stderr or you aren't actually triggering an error. This is just the way the program was written. What is the program?
再次编辑:忽略上述内容,因为communication() 正在捕获所有这些。我会说问题肯定是您选择的程序从不写入 stderr 或者您实际上没有触发错误。这只是程序的编写方式。程序是什么?