Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

linux - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...