关于子进程:不带输出的Python os.system

Python os.system without the output

我正在运行这个:

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

它会按需重启网络服务器,就像如果我直接从终端运行命令那样,它将输出以下内容:

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

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


务必避免使用os.system(),而应使用子进程:

1
2
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

1
2
3
4
#!/usr/bin/env python3
from subprocess import DEVNULL, STDOUT, check_call

check_call(['/etc/init.d/apache2', 'restart'], stdout=DEVNULL, stderr=STDOUT)


根据您的操作系统(这就是为什么Noufal所说,您应该改用子进程),您可以尝试类似

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

或(也将错误静音)

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


您应该使用subprocess模块,通过该模块可以灵活地控制stdoutstderros.system已过时。

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


这是几年前我拼凑而成的系统调用函数,已在各种项目中使用。如果您根本不需要命令的任何输出,则可以说out = syscmd(command),然后对out不执行任何操作。

经过测试并在Python 2.7.12和3.5.2中工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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