2

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?

wkl
  • 77,184
  • 16
  • 165
  • 176
Alon_T
  • 1,430
  • 4
  • 26
  • 47
  • 1
    You probably meant `> /dev/null` in your `sh` equivalent, not `< /dev/null`, which would redirect `stdin`, not `stdout`. – abarnert Jan 06 '13 at 13:15

1 Answers1

7

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Great thanks...but if I use the 2.7 solution will it still work with 3.x? – Alon_T Jan 06 '13 at 13:15
  • @user1432779: Yes. I'll put full compatibility details in. – abarnert Jan 06 '13 at 13:15
  • Thanks..but I think I have a problem..I'm trying to write a script on the server that would start another server..however when I run it through the shell on the process I get after a few seconds :Exception AttributeError: "'Popen' object has no attribute '_child_created'" in > ignored {ans:0} – Alon_T Jan 06 '13 at 13:29
  • @user1432779: I don't understand what you're saying. What do you mean "when I run it through the shell on the process"? If you have a new problem that's too hard to explain in a comment, create a new question, or edit your existing one. – abarnert Jan 06 '13 at 13:56
  • the shell of the server sorry – Alon_T Jan 06 '13 at 13:58
  • I've posted a new one...it seems that this solution creates a new problem :http://stackoverflow.com/questions/14182780/error-when-running-call-in-python-subprocess – Alon_T Jan 06 '13 at 13:59