30

我正在运行这个:

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

它应该重新启动网络服务器,就像我直接从终端运行命令一样,它会输出以下内容:

* Restarting web server apache2 ... waiting [ OK ]

但是,我不希望它在我的应用程序中实际输出。我怎样才能禁用它?谢谢!

4

5 回答 5

50

一定要避免os.system(),并使用 subprocess 代替:

with open(os.devnull, 'wb') as devnull:
    subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT)

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)
于 2011-04-08T15:06:24.080 回答
30

根据您的操作系统(这就是为什么正如 Noufal 所说,您应该使用 subprocess 代替)您可以尝试类似

 os.system("/etc/init.d/apache restart > /dev/null")

或(也使错误静音)

os.system("/etc/init.d/apache restart > /dev/null 2>&1")
于 2011-04-08T15:05:30.853 回答
25

您应该使用subprocess可以灵活控制stdout和的模块。已弃用。stderros.system

subprocess模块允许您创建一个代表正在运行的外部进程的对象。您可以从它的 stdout/stderr 读取它,写入它的 stdin,发送信号,终止它等。模块中的主要对象是Popen. 还有许多其他方便的方法,例如 call 等。文档非常全面,其中包括有关替换旧功能(包括os.system的部分。

于 2011-04-08T14:56:50.340 回答
1

这是我几年前拼凑起来的一个系统调用函数,并在各种项目中使用过。如果您根本不想要命令的任何输出,您可以只说out = syscmd(command)然后对out.

在 Python 2.7.12 和 3.5.2 中测试并运行。

def syscmd(cmd, encoding=''):
    """
    Runs a command on the system, waits for the command to finish, and then
    returns the text output of the command. If the command produces no text
    output, the command's return code will be returned instead.
    """
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
        close_fds=True)
    p.wait()
    output = p.stdout.read()
    if len(output) > 1:
        if encoding: return output.decode(encoding)
        else: return output
    return p.returncode
于 2017-09-14T20:09:39.147 回答
0

我在使用 Windows 机器时遇到了类似的问题,发现这是解决问题的最简单方法

import subprocess
cmd='gdalwarp -overwrite -s_srs EPSG:4283 -t_srs EPSG:28350 -of AAIGrid XXXXX.tif XXXXX.asc'
subprocess.run(cmd,shell=True)

更改cmd为您想要运行的任何内容。我迭代了 > 1000 次,并且没有出现命令提示符窗口,我能够节省大量时间。

于 2021-09-27T08:17:39.433 回答