Python os.system不显示输出
我正在运行这个:
os.system("/etc/init.d/apache2 restart")
它会重启网络服务器,像我直接在终端运行命令一样,输出如下信息:
* 正在重启网络服务器 apache2 ...
等待 [ 好 ]
但是,我不想在我的应用程序中实际显示这些信息。我该怎么做才能关闭它呢?谢谢!
6 个回答
39
根据你使用的操作系统(这就是为什么Noufal建议你使用subprocess的原因),你可以尝试类似下面的代码:
os.system("/etc/init.d/apache restart > /dev/null")
或者(如果你想把错误信息也隐藏起来的话)
os.system("/etc/init.d/apache restart > /dev/null 2>&1")
65
尽量避免使用 os.system()
,而是使用 subprocess
。
with open(os.devnull, 'wb') as devnull:
subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT)
这段代码是 /etc/init.d/apache2 restart &> /dev/null
的 subprocess
版本。
在 Python 3.3 及以上版本中,有一个叫 subprocess.DEVNULL
的东西:
#!/usr/bin/env python3
from subprocess import DEVNULL, STDOUT, check_call
check_call(['/etc/init.d/apache2', 'restart'], stdout=DEVNULL, stderr=STDOUT)