抑制python子进程调用中的输出
对于以下命令:
subprocess.call(shlex.split(
"""/usr/local/itms/bin/iTMSTransporter -m lookupMetadata
-apple_id %s -destination %s"""%(self.apple_id, self.destination))
它将整个输出打印到终端窗口中.我将如何在这里抑制所有输出?我尝试做 subprocess.call(shlex.split(<command> >/dev/null 2&1
)),但它没有产生所需的结果.我在这里怎么做?
It prints the entire output into the Terminal window. How would I suppress ALL output here? I tried doing subprocess.call(shlex.split(<command> > /dev/null 2&1
)), but it didn't produce the required results. How would I do this here?
您可以将 stdout=
和 stderr=
参数用于 subprocess.call()
将 stdout
或 stderr
定向到您选择的文件描述符.所以也许是这样的:
You can use the stdout=
and stderr=
parameters to subprocess.call()
to direct stdout
or stderr
to a file descriptor of your choice. So maybe something like this:
import os
devnull = open(os.devnull, 'w')
subprocess.call(shlex.split(
'/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
'-apple_id %s -destination %s' % (self,apple_id, self.destination)),
stdout=devnull, stderr=devnull)
使用 subprocess.PIPE
,如果您不从管道中读取数据,则可能会导致程序在生成大量输出时阻塞.
Using subprocess.PIPE
, if you're not reading from the pipe, could cause your program to block if it generates a lot of output.
更新
正如@yanlend 在评论中提到的,较新的 (3.x) 版本的 Python 包括 subprocess.DEVNULL
以更方便和便携的方式解决这个问题.在这种情况下,代码将如下所示:
As @yanlend mentions in a comment, newer (3.x) versions of Python include subprocess.DEVNULL
to solve this problem in a more convenient and portable fashion. In that case, the code would look like:
subprocess.call(shlex.split(
'/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
'-apple_id %s -destination %s' % (self,apple_id, self.destination)),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)