Why does the below MWE not redirect output to /dev/null.
#!/usr/bin/env python
import os
if __name__ == "__main__":
os.system ( 'echo hello &>/dev/null' )
Not sure, but another (better) way to do it is:
from os import devnull
from subprocess import call
if __name__ == "__main__":
with open(devnull, 'w') as dn:
call(['echo', 'hello'], stdout=dn, stderr=dn)
This opens /dev/null
for writing, and redirects output of the spawned process to there.
UPDATE based on comments from @abarnert
In the specific case of echo
, to get identically the same behavior you will want to use shell=True
because otherwise it will call /bin/echo
, not the shell builtin:
call('echo hello', shell=True, stdout=dn, stderr=dn)
Also, on Python 3.3+, you can do
from subprocess import call, DEVNULL
if __name__ == "__main__":
call('echo hello', shell=True, stdout=DEVNULL, stderr=DEVNULL)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.