4

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()
Gilad Naor
21.8k15 gold badges49 silver badges54 bronze badges
asked May 27, 2009 at 6:51
1
  • 1
    Thanks 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 :) ~nolo Commented May 28, 2009 at 20:02

2 Answers 2

8

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
answered Jun 11, 2014 at 20:03
Sign up to request clarification or add additional context in comments.

Comments

2

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?

answered May 27, 2009 at 6:56

1 Comment

what would you suggest? spent quite a bit of time reading up; yet most point to deprecated usage. o.spawn etc.. thanks in advance :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.