2

I have a python script (.py) which runs normally on the console. When I try running the script using pythonw by changing the extension to (.pyw), it stopped working. My guess is that the print statements are causing pythonw to die based on results returned from Google Search.

Is there a convenient way to disable the print statements so that pythonw can run? I have too many print statements in the script. Changing them one by one is not practical, particularly if I want to switch back to using normal python.

Thanks.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • I have no clue what pythonw, but it sounds like you want to print to null, effectively making this question a duplicate. http://stackoverflow.com/questions/6735917/redirecting-stdout-to-nothing-in-python – Leon Nov 10 '14 at 05:22
  • `"My guess is that the print statements are causing pythonw to die"` - Nope, doesn't seem to be the case in my quick test. – Jonathon Reinhart Nov 10 '14 at 05:24

3 Answers3

1

create your own print function, say out, and then change all prints to out. the out method can then be changed once to output to console or to a file.

Ayman
  • 11,265
  • 16
  • 66
  • 92
1

I discovered an answer from another StackOverflow thread which worked well for me. I have upvoted the answer. The credit is not mine. If you want to upvote, go to that link and upvote. See link below.

Can I get the output of "print" statement in pythonw?

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.

Community
  • 1
  • 1
guagay_wk
  • 26,337
  • 54
  • 186
  • 295
1

Just redirect all output to /dev/null. Python has a platform agnostic way to do this.

import os
import sys

# Only redirect for pythonw not regular python.
if os.path.splitext(os.path.basename(sys.executable))[0] == 'pythonw':
    sys.stdout = open(os.devnull, 'w')
    sys.stderr = open(os.devnull, 'w')
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118