Python os.system without the output

我怕爱的太早我们不能终老 提交于 2019-11-29 03:09:11
lunaryorn

Avoid os.system() by all means, and use subprocess instead:

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

This is the subprocess equivalent of the /etc/init.d/apache2 restart &> /dev/null.

There is 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)

You should use the subprocess module using which you can control the stdout and stderr in a flexible fashion. os.system is deprecated.

The subprocess module allows you to create an object which represents a running external process. You can read it from it's stdout/stderr, write to it's stdin, send it signals, terminate it etc. The main object in the module is Popen. There are a bunch of other convenience methods like call etc. The docs are very comprehensive and include a section on replacing the older functions (including os.system).

mb14

Depending on your OS (and that's why as Noufal said, you should use subprocess instead) you can try something like

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

or (to mute also the error)

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

Here is a system call function I pieced together several years ago and have used in various projects. If you don't want any output from the command at all you can just say out = syscmd(command) and then do nothing with out.

Tested and works in Python 2.7.12 and 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!