capture stderr from python subprocess.Popen(comman

2019-04-10 02:54发布

问题:

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()

回答1:

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


回答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?