Archive

Posts Tagged ‘redirect to /dev/null’

Redirect stdout to a file

August 17, 2011 1 comment

Problem
Your script produces some output to the standard output and you want to redirect it to a file. For instance, you want to suppress the output to /dev/null. However, you want to do this redirection from your script and not in the shell.

Solution
Add the following lines to the beginning of your script (before the first print call):

old_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')

Of course, instead of os.devnull you can specify a normal text file too. To restore printing to stdout, point sys.stdout to old_stdout.

Related
In this thread you will see a solution for redirecting the stdout to a string.