Python os.system without the output
我正在运行这个:
1 | os.system("/etc/init.d/apache2 restart") |
它会按需重启网络服务器,就像如果我直接从终端运行命令那样,它将输出以下内容:
但是,我不希望它实际在我的应用程序中输出。 如何禁用它?
谢谢!
务必避免使用
1 2 | with open(os.devnull, 'wb') as devnull: subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT) |
这是与
在Python 3.3+上有
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") |
您应该使用
这是几年前我拼凑而成的系统调用函数,已在各种项目中使用。如果您根本不需要命令的任何输出,则可以说
经过测试并在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 |