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
  • 20,752
  • 14
  • 46
  • 53
  • 1
    Thanks for your answer SpliFF spot on. For clarity "PyMOTW: subprocess by Doug Hellmann" here [ http://www.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 –  May 28 '09 at 20:02

2 Answers2

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
Patrick Wolf
  • 2,530
  • 2
  • 28
  • 27
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?

SpliFF
  • 38,186
  • 16
  • 91
  • 120
  • what would you suggest? spent quite a bit of time reading up; yet most point to deprecated usage. o.spawn etc.. thanks in advance :) –  May 27 '09 at 21:31