Alon_T
Alon_T

Reputation: 1440

run a process to /dev/null in python

How do I run the following in Python?

/some/path/and/exec arg > /dev/null

I got this:

call(["/some/path/and/exec","arg"])

How do I insert the output of the exec process to /dev/null and keep the print output of my python process as usual? As in, don't redirect everything to stdout?

Upvotes: 2

Views: 4212

Answers (1)

abarnert
abarnert

Reputation: 365787

For Python 3.3 and later, just use subprocess.DEVNULL:

call(["/some/path/and/exec","arg"], stdout=DEVNULL, stderr=DEVNULL)

Note that this redirects both stdout and stderr. If you only wanted to redirect stdout (as your sh line implies you might), leave out the stderr=DEVNULL part.

If you need to be compatible with older versions, you can use os.devnull. So, this works for everything from 2.6 on (including 3.3):

with open(os.devnull, 'w') as devnull:
    call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull)

Or, for 2.4 and later (still including 3.3):

devnull = open(os.devnull, 'w')
try:
    call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull)
finally:
    devnull.close()

Before 2.4, there was no subprocess module, so that's as far back as you can reasonably go.

Upvotes: 7

Related Questions