0

I'm trying to run a pygame program using pythonw to avoid having the console window show up. This causes a weird issue related to print statements.

Basically, the program will just exit after a few seconds with no error message. The more printing I do, the faster it happens. If I run it in idle or at the command prompt (or in linux) the program works fine. This problem only happens when launched with pythonw (right-click, Open With, pythonw).

I'm using python 2.7.11 on Windows XP 32-bit. pygame 1.9.1release.

Is there a workaround for this? Why does the program simply terminate with no error?

import pygame
from pygame.locals import *

succeeded, failed = pygame.init()
display_surface = pygame.display.set_mode((320, 240))
clock = pygame.time.Clock()

terminate = False
while terminate is False:
    for event in pygame.event.get():
        if event.type == QUIT:
            terminate = True    
    area = display_surface.fill((0,100,0))
    pygame.display.flip()                 
    elapsed = clock.tick(20)              
    print str(elapsed)*20
pygame.quit()
  • have you try to remove all `print` ? – furas Jan 01 '16 at 09:02
  • http://stackoverflow.com/questions/3674667/can-i-get-the-output-of-print-statement-in-pythonw – furas Jan 01 '16 at 11:15
  • @furas Yes if the print statements are removed the problem disappears. However it took me a very long time to track down the issue to the print statements. If you are printing very little it can happen randomly. – user5541269 Jan 01 '16 at 14:40

1 Answers1

0

You don't need to remove print statements. Save them for later debugging. ;-)

Two steps to solve this problem:

  • Firstly, keep all the code in py file - don't change it to pyw now; Say it is actualCode.py
  • Then, create a new file runAs.pyw with the following lines in it
# In runAs.pyw file, we will first send stdout to StringIO so that it is not printed

import sys  # access to stdout
import StringIO  # StringIO implements a file like class without the need of disc

sys.stdout = StringIO.StringIO()  # sends stdout to StringIO (not printed anymore)

import actualCode  # or whatever the name of your file is, see further details below

Note that, just importing actualCode runs the file, so, in actualCode.py you should not enclose the code which is executed, in what I call is it main running file condition. For example,

# In actualCode.py file
....
....
....
if __name__ == '__main__':  # Don't use this condition; it evaluates to false when imported
    ...  # These lines won't be executed when this file is imported,
    ...  # So, keep these lines outside
# Note: The file in your question, as it is, is fine
Price
  • 1