我正在运行这个:
os.system("/etc/init.d/apache2 restart")它会重新启动run服务器,就像我直接从终端运行命令一样,输出如下:
* Restarting web server apache2 ... waiting [ OK ]
然而,我不希望它在我的应用程序中实际输出它。如何将其禁用?谢谢!
发布于 2011-04-08 23:06:24
一定要避免使用os.system(),改用子进程:
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等效项。
有一个subprocess.DEVNULL on Python 3.3+
#!/usr/bin/env python3
from subprocess import DEVNULL, STDOUT, check_call
check_call(['/etc/init.d/apache2', 'restart'], stdout=DEVNULL, stderr=STDOUT)发布于 2011-04-08 23:05:31
根据您的操作系统(这就是为什么如Noufal所说,您应该改用子进程),您可以尝试如下所示
os.system("/etc/init.d/apache restart > /dev/null")或者(也可以静音错误)
os.system("/etc/init.d/apache restart > /dev/null 2>&1")发布于 2011-04-08 22:56:50
您应该使用subprocess模块,使用它可以以灵活的方式控制stdout和stderr。os.system已弃用。
subprocess模块允许您创建一个表示正在运行的外部进程的对象。你可以从它的stdout/stderr中读取它,写它的stdin,发送信号,终止它等等。模块中的主要对象是Popen。还有许多其他方便的方法,如call等。docs非常全面,并且包含一个section on replacing the older functions (including os.system)。
https://stackoverflow.com/questions/5596911
复制相似问题