pythonw.exe doesn't have a console so I can't see the output of print. But my program is OKAY in python.exe, failed in pythonw.exe. I just want to see the logs from python interpreter and the log printed by my "print" statement, is it doable?
4 Answers
You can globally redirect stdout by assigning to sys.stdout:
import sys
sys.stdout = open("mylog.txt", "w")
Then the rest of your program's stdout, including print statements, will go to mylog.txt.

- 364,293
- 75
- 561
- 662
You can redirect the output to any class that implements a .write method. For example, I redirect both sys.stdout and sys.stderr to a class that writes the results into a rich textbox, with the normal output in black and the errors in red.
logControl = None
def LogWrite(text, color):
logControl.SetDefaultStyle(wx.TextAttr(color, wx.NullColour))
logControl.WriteText(text)
class RedirectStdOut:
def write(self,string):
LogWrite(string, "BLACK")
class RedirectStdErr:
def write(self,string):
LogWrite(string, "RED")
....
sys.stdout = RedirectStdOut()
sys.stderr = RedirectStdErr()
In this case, logControl is just a reference to a rich textbox that I can assume exists. You could write to both the control and a file, redirect to dbgview or do pretty much anything you want with it.

- 1,785
- 20
- 18
You can redirect the output of print to any stream. For example
logfile = open("logfile.txt", "w")
print >>logfile, "This is a log test"
Although most of the time it would be more appropriate to use python's built-in logging facilities from the logging
module.

- 215
- 1
- 9
I found that a plain print statement that is too long will crash the program. You need to redirect the output. To test this idea create a simple program
import time
time.sleep(5)
Save it as test.pyw. When you run this program it will show up on the task manager. Now modify it by adding a print statement. This text file has over 100 lines in it.
import time
string = ''
filename = 'pathto/text.txt'
f = open(filename,'r')
for line in f:
string = string + ' ' + line
f.close()
print string
time.sleep(5)
The program will crash.

- 1,587
- 2
- 13
- 24
-
1LOL, you have a tabulator in your filename? :D Your program is very likely to crash otherwise. The correct way to accomplish what you did is using `' '.join`. – Gandaro Feb 17 '12 at 14:17