Why when import pygame, it prints the version and

2019-02-12 00:22发布

问题:

Why is there a message when I import pygame, it prints the version and welcome message. The message reads

"pygame 1.9.4 Hello from the pygame community.
 https://www.pygame.org/contribute.html" 

How can I disable this message?

回答1:

I didn't see a natural way to do it (yours is the only Google result for this that I could find), but I did achieve the same thing by temporarily disabling stdout while importing pygame.

import os, sys
with open(os.devnull, 'w') as f:
    # disable stdout
    oldstdout = sys.stdout
    sys.stdout = f

    import pygame

    # enable stdout
    sys.stdout = oldstdout

Here's the alternative suggested by @Mad Physicist:

import contextlib
with contextlib.redirect_stdout(None):
    import pygame


回答2:

You can navigate to the pygame library folder, something like this for 3.6 32 bit version:

Python36-32\Lib\site-packages\pygame

and edit the __init__.py file and remove the last line to get rid of this message.



回答3:

  1. import pygame
  2. Get the location of the init file: f = pygame.__file__
  3. Open f and comment out the print on the last two lines of the file


回答4:

# remove pygame installed with "pip install..."
python pip uninstall pygame
# remove all folder with pygame
sudo apt-get update -y; sudo apt-get upgrade -y
sudo apt-get install python-pyame

The version installed with the last line will work without announcing its name.