抑制python子进程调用中的输出 [英] Suppressing output in python subprocess call

查看:40
本文介绍了抑制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()stdoutstderr 定向到您选择的文件描述符.所以也许是这样的:

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)

这篇关于抑制python子进程调用中的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆