capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
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()
-
1Thanks for your answer SpliFF spot on. For clarity "PyMOTW: subprocess by Doug Hellmann" here [ oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html ] from Tkinter import * import subprocess proc=subprocess.Popen('TestSomeCommandThatDoesNotExisit',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,) stdout_value, stderr_value = proc.communicate() root = Tk() text = Text(root) text.pack() text.insert(END, repr(stdout_value)) root.mainloop() I was not merging stderr=sub.STDOUT Thanks again ombre :) ~noloAnonymous– Anonymous2009年05月28日 20:02:49 +00:00Commented May 28, 2009 at 20:02
2 Answers 2
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
Comments
Are you 100% sure 'datdsade' actually writes to stderr? If so then possibly it's buffering its stderr, or blocking on it.
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.
Alternatively stderr=sub.STDOUT will merge your errors with the 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?