I've got a class that redirects stdout/stderr to itself:
PHP Code:
class OutputLog(wx.TextCtrl):
def __init__(self, parent, id=-1):
wx.TextCtrl.__init__(self, parent, id, style=wx.TE_MULTILINE|wx.TE_READONLY)
self.SetBackgroundColour(u'black')
self.SetForegroundColour(u'white')
self.stdout = sys.stdout
self.stderr = sys.stderr
def write(self, string):
self.AppendText(string)
def ToggleOutput(self, event=None):
if (sys.stdout == self):
sys.stdout = self.stdout
sys.stderr = self.stderr
else:
sys.stdout = self
sys.stdout = self
The problem is that not everything is redirected to it. It works when I use the "print" function, but not for system calls or errors.
Here is an example:
PHP Code:
...
self.outputlog = OutputLog(self)
self.outputlog.ToggleOutput() # Set stdout/stderr to print to log
...
def PrintSomething(self, event=None):
print 'Hello from Python'
os.system('echo "Hello from system"')
subprocess.Popen(['echo', 'Hello from subprocess'])
print hello # Force a NameError
"Hello from Python" is printed in the output log, but "Hello from system", "Hello from subprocess" and the error traceback are printed in the system terminal. Is there a way to redirect all of this as well?
----- EDIT -----
I figured out how to manually do tracebacks, but it would be nice if all tracebacks were automatically sent to the OutputLog:
PHP Code:
...
try:
print hello
except NameError:
traceback.print_exc(file=sys.stdout) # Can also use "file=self.outputlog"
----- EDIT -----
Okay, figured out how to get it from os and subprocess modules, although once again it is not automatic, I have to put the output into a variable then print it:
PHP Code:
...
o = os.popen('echo "Hello from system"').read()
print o
s = subprocess.Popen(['echo', 'Hello from subprocess'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print s.stdout.read()
I'm not going to mark this thread as solved for a couple of days in case someone has a better answer. Is there a way to redirect the output of os.popen or subprocess.Popen without having to put it into a variable?
Bookmarks