0

Apparently the version of pygame I'm using has an issue where debug statements have been left in - How to suppress console output in Python? while using joystick.get_axis. That is the issue, but I have been unsuccessful in trying to use the methods presented in those answers. Each of the methods still printed the SDL_JoystickGetAxis value.

I also tried this blog but I was still outputting to the console. Thinking it may be an issue with stdout vs stderr, I tried suppressing stdout then stderr then both, to no avail.

Basically my code is constantly printing SDL_JoystickGetAxis value:0 or whatever the axis value is. How do I suppress these debug statements?

import os
import sys
from contextlib import contextmanager

@contextmanager
def suppress_stdout():
    with open(os.devnull, 'w') as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull 
        try:
            yield
        finally:
            sys.stdout = old_stdout

Later on in my code I use that function:

    if speedchange == False and headingchange == False:
        time.sleep(0.1)
        with suppress_stdout():
            speed_ax = joys.get_axis(1)
            head_ax = joys.get_axis(0)

Which still outputs debug statements

Community
  • 1
  • 1
Murphy
  • 31
  • 9

2 Answers2

0

I'm not sure why the code from the blog you linked doesn't work, but you can always just drop this at the top of your code:

sys.stdout = os.devnull
sys.stderr = os.devnull

If you do then need to output error messages, or the like, you can just do this:

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

Just in case you are using the context manager linked in the blog wrong, this is how you're supposed to use it:

with suppress_stdout():
    # Do blah foo and bar here
Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42
  • I just added the code I'm using to the question. I think I am using the blog code the correct way, so I wasn't sure if debug messages have some weird special properties. I also tried your solution, sandwiching the `joys.get_axis` part in-between, which also did not work. – Murphy Sep 16 '15 at 13:29
0

This worked for me in python 3.5 and python 2.7

import sys, os
stdout = sys.__stdout__
stderr = sys.__stderr__
print("start")
sys.stdout = open(os.devnull,'w')
sys.stderr = open(os.devnull,'w')
print("don't want")
sys.stdout = stdout
sys.stderr = stderr
print("want")

The output is

start
want
saulspatz
  • 5,011
  • 5
  • 36
  • 47