简体   繁体   English

使用os.system()抑制输出

[英]Supressing output with os.system()

Why does the below MWE not redirect output to /dev/null. 下面的MWE为什么不将输出重定向到/ 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. 这将打开/dev/null进行写入,并将生成的进程的输出重定向到那里。


UPDATE based on comments from @abarnert 根据@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: echo的特定情况下,要获得相同的行为,您将要使用shell=True因为否则它将调用/bin/echo ,而不是内置的shell:

call('echo hello', shell=True, stdout=dn, stderr=dn)

Also, on Python 3.3+, you can do 另外,在Python 3.3+上,您可以执行

from subprocess import call, DEVNULL

if __name__ == "__main__":
    call('echo hello', shell=True, stdout=DEVNULL, stderr=DEVNULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM