从python subprocess.Popen捕获stderr(命令,stderr = subprocess.PIPE,stdout = subprocess.PIPE)

4 python subprocess

我在这里发过这么多次了; 但未能从命令中捕获故意错误.到目前为止我找到的最好的部分工作..

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()
Run Code Online (Sandbox Code Playgroud)

Pat*_*olf 8

这对我很有用:

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
Run Code Online (Sandbox Code Playgroud)