Matyas
Matyas

Reputation: 13702

How to redirect stderr/stdout of a Gtk.Window() call in python?

I am creating a Gtk.Window() in python. Because the theme I am using, I get a handful of warnings like:

Gtk-WARNING **: Theme parsing error: other-applications.css:35:21: 'px' is not a valid color name

But that is ok. I only wish to hide this information from the command line output.

What I've tried and did not work was:

# open /dev/null
devnull = open(os.devnull, 'w')

# redirect the stderr/out of the current process
sys.stdout = devnull
sys.stderr = devnull

# open the window
window = Gtk.Window()

print 'hello world'

# eventually restore previous stderr/out
...

The problem is that 'hello world' is not printed (as expected) but the above mentioned warnings still appear.

Any suggestions?

Upvotes: 0

Views: 1003

Answers (2)

LiuLang
LiuLang

Reputation: 773

@Matyas.

That error is caused by old version of Gtk3, likely happens in Debian Wheezy or Ubuntu 12.04. In Gtk3.4 and earlier, px is not supported as a unit.

A simple way to fix it is to create two css files, one with px, one without. While loading style file as CssProvider in python, check current gtk3 version, like this:

if Gtk.MINOR_VERSION < 6:
    # load other-applications-3.4.css
else:
    # load other-applications.css

I've met this situation in my project before.

Upvotes: 1

mguijarr
mguijarr

Reputation: 7908

Redirecting sys.stdout and sys.stderr only affects Python code; in your case, the errors you see come from Gtk (at a lower level).

You have to redirect using the raw file descriptors. Look at this: How do I prevent a C shared library to print on stdout in python?

Basically here is some code to redirect stdout at the lowest level for C code, but not for Python code (took answer from Dietrich Epp):

def redirect_stdout():
    # Redirecting stdout
    sys.stdout.flush() # <--- important when redirecting to files
    newstdout = os.dup(1)
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, 1)
    os.close(devnull)
    sys.stdout = os.fdopen(newstdout, 'w')

Upvotes: 2

Related Questions