|
|
紧张的树叶 · Java AES-256-CBC ...· 1 年前 · |
|
|
温文尔雅的大白菜 · sqlserver运行超大sql文件_sql ...· 2 年前 · |
|
|
逃课的滑板 · 范冰冰红唇魅影登《风尚志》 ...· 2 年前 · |
|
|
豪气的苹果 · 生信SCI文章解读 - 知乎· 2 年前 · |
我正在运行这个:
os.system("/etc/init.d/apache2 restart")
它会重新启动run服务器,就像我直接从终端运行命令一样,输出如下:
* Restarting web server apache2 ...
waiting [ OK ]
然而,我不希望它在我的应用程序中实际输出它。如何将其禁用?谢谢!
您应该使用
subprocess
模块,使用它可以以灵活的方式控制
stdout
和
stderr
。
os.system
已弃用。
subprocess
模块允许您创建一个表示正在运行的外部进程的对象。你可以从它的stdout/stderr中读取它,写它的stdin,发送信号,终止它等等。模块中的主要对象是
Popen
。还有许多其他方便的方法,如call等。
docs
非常全面,并且包含一个
section on replacing the older functions (including
os.system
)
。
根据您的操作系统(这就是为什么如Noufal所说,您应该改用子进程),您可以尝试如下所示
os.system("/etc/init.d/apache restart > /dev/null")
或者(也可以静音错误)
os.system("/etc/init.d/apache restart > /dev/null 2>&1")
一定要避免使用
os.system()
,改用子进程:
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
等效项。
有一个
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)
这是我几年前拼凑的一个系统调用函数,并在各种项目中使用过。如果您根本不想要该命令的任何输出,那么您可以只说
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()
|
|
豪气的苹果 · 生信SCI文章解读 - 知乎 2 年前 |