stdout, stderr redirection in python

hacker_compDuring the development of google-cli, I faced an issue with debug and error messages from Firefox as well as Chromium based browsers. When you launch any URL in the browser using webbrowser.open(url) family of APIs, the following show up on the terminal:

// Firefox
(process:8748): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed

// Chromium
Created new window in existing browser session.
[1:2:1013/004438:ERROR:channel.cc(300)] RawChannel read error (connection broken)

I checked in several forums including StackOverflow but couldn’t get a complete solution that works for both the browser families. On trial and error, I found one way to hide these warnings and errors is to redirect stdout and stderr to /dev/null. Here’s the OS independent code snippet:

import os

    def open(self):
        _stderr = os.dup(2)
        os.close(2)
        _stdout = os.dup(1)
        os.close(1)
        fd = os.open(os.devnull, os.O_RDWR)
        os.dup2(fd, 2)
        os.dup2(fd, 1)
        try:
            webbrowser.open(self.url)
        finally:
            os.close(fd)
            os.dup2(_stderr, 2)
            os.dup2(_stdout, 1)
            os.close(_stderr)
            os.close(_stdout)

Now the warnings and error do not appear on the console anymore.

2 thoughts on “stdout, stderr redirection in python”

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s