Home > python > Redirect stdout to a file

Redirect stdout to a file

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.

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.

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

  1. July 4, 2017 at 14:12

    thank you vry much you saved my day!!!!

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: