use*_*108 19 python subprocess os.system
我正在运行这个:
os.system("/etc/init.d/apache2 restart")
Run Code Online (Sandbox Code Playgroud)
它会重新启动Web服务器,就像我应该直接从终端运行命令一样,它会输出:
* Restarting web server apache2 ...
waiting [ OK ]
但是,我不希望它在我的应用程序中实际输出它.我该如何禁用它?谢谢!
lun*_*orn 35
一定要避免os.system(),而是使用子流程:
with open(os.devnull, 'wb') as devnull:
subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT)
Run Code Online (Sandbox Code Playgroud)
这subprocess相当于/etc/init.d/apache2 restart &> /dev/null.
有subprocess.DEVNULL关于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)
Run Code Online (Sandbox Code Playgroud)
mb1*_*b14 22
根据你的操作系统(这就是Noufal所说的,你应该使用subprocess)你可以尝试类似的东西
os.system("/etc/init.d/apache restart > /dev/null")
Run Code Online (Sandbox Code Playgroud)
或(也使错误静音)
os.system("/etc/init.d/apache restart > /dev/null 2>&1")
Run Code Online (Sandbox Code Playgroud)
Nou*_*him 21
您应该使用的subprocess使用,你可以控制的模块stdout,并stderr以灵活的方式.os.system已弃用.
该subprocess模块允许您创建表示正在运行的外部进程的对象.你可以从它的stdout/stderr读取它,写入它的stdin,发送信号,终止它等.模块中的主要对象是Popen.还有许多其他方便的方法,如调用等.文档非常全面,包括一个关于替换旧函数(包括os.system)的部分.