Hubro
Hubro

Reputation: 59343

Can I redirect all output to /dev/null from within python?

I'm writing a Python script that'll fork a child process. The parent process should be able to write stuff like Started child at xxxxx, but the child process output should be redirected to /dev/null. How can I do that from within python?

Upvotes: 3

Views: 3433

Answers (2)

user8234870
user8234870

Reputation:

If someone is looking for a cross-platform way to redirect the output to the null file, then we can use os.devnull attribute to specify that we want to output to be redirected to the null file.

import sys
import os

stderr = sys.stderr
stdout = sys.stdout

# print(os.devnull)

print("Hell o World!")

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

print("This is redirected to null")

Output:

Hell o World!

First, we are creating a backup for the default standard output and standard error:

stderr = sys.stderr
stdout = sys.stdout

Then we display msg to the default standard output:

print("Hell o World!")

Next, we are redirecting the output messages and the error messages to the null file:

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

Here we are verifying that the output is redirected to the null file:

print("This is redirected to null")

If in case, you want to find where the null file is located it may return different results because this depends on the operating system on which the Python program is running:

print(os.devnull)

It is also possible that you want to reset where output and error messages are displayed to the default standard output and standard error in that case you can use this approach:

import sys
import os

stderr = sys.stderr
stdout = sys.stdout

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

print("This is redirected to null.")

sys.stderr = stderr
sys.stdout = stdout

print("This is redirected to the standard output.")

Output:

This is redirected to the standard output.

Upvotes: 0

Rafe Kettler
Rafe Kettler

Reputation: 76955

import sys
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout = open('/dev/null', 'w')
sys.stderr = open('/dev/null', 'w')

Upvotes: 13

Related Questions