Python os.system不显示输出

39 投票
6 回答
97245 浏览
提问于 2025-04-16 15:21

我正在运行这个:

os.system("/etc/init.d/apache2 restart")

它会重启网络服务器,像我直接在终端运行命令一样,输出如下信息:

* 正在重启网络服务器 apache2 ...

等待 [ 好 ]

但是,我不想在我的应用程序中实际显示这些信息。我该怎么做才能关闭它呢?谢谢!

6 个回答

25

你应该使用 subprocess 模块,这样你可以灵活地控制 stdout(标准输出)和 stderr(错误输出)。而 os.system 已经不推荐使用了。

subprocess 模块让你可以创建一个对象,这个对象代表一个正在运行的外部进程。你可以从它的标准输出和错误输出中读取信息,向它的标准输入写入数据,发送信号,终止它等等。这个模块的主要对象是 Popen。还有一些其他方便的方法,比如 call 等等。相关的 文档 非常全面,还包括了一个关于如何用 subprocess 模块替代旧函数(包括 os.system)的 部分

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/nullsubprocess 版本。

在 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)

撰写回答