如何抑制或捕获subprocess.run()的输出?

发布于 2021-01-29 15:07:31

从文档中的示例subprocess.run()来看,似乎不应该有任何输出

subprocess.run(["ls", "-l"])  # doesn't capture output

但是,当我在python shell中尝试时,列表会被打印出来。我想知道这是否是默认行为,以及如何抑制的输出run()

关注者
0
被浏览
66
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是按清洁度递减的顺序 抑制 输出的方法。他们假设您使用的是Python 3。

    1. 您可以重定向到特殊subprocess.DEVNULL目标。

      import subprocess

      subprocess.run([‘ls’, ‘-l’], stdout=subprocess.DEVNULL)

      The above only redirects stdout…

      this will also redirect stderr to /dev/null as well

      subprocess.run([‘ls’, ‘-l’], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

      Alternatively, you can merge stderr and stdout streams and redirect

      the one stream to /dev/null

      subprocess.run([‘ls’, ‘-l’], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)

    2. 如果要使用完全手动的方法,可以/dev/null自己打开文件句柄来重定向到。其他所有内容都与方法1相同。

      import os
      import subprocess

      with open(os.devnull, ‘w’) as devnull:
      subprocess.run([‘ls’, ‘-l’], stdout=devnull)


    以下是按清洁度递减的顺序 捕获 输出(以供以后使用或解析)的方法。他们假设您使用的是Python 3。

    1. 如果您只是想同时捕获STDOUT和STDERR,并且您使用的是Python> = 3.7,请使用capture_output=True

      import subprocess

      result = subprocess.run([‘ls’, ‘-l’], capture_output=True)
      print(result.stdout)
      print(result.stderr)

    2. 您可以用来subprocess.PIPE独立捕获STDOUT和STDERR。这 确实 对Python版本<3.7,如Python 3.6的工作。

      import subprocess

      result = subprocess.run([‘ls’, ‘-l’], stdout=subprocess.PIPE)
      print(result.stdout)

      To also capture stderr…

      result = subprocess.run([‘ls’, ‘-l’], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      print(result.stdout)
      print(result.stderr)

      To mix stdout and stderr into a single string

      result = subprocess.run([‘ls’, ‘-l’], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
      print(result.stdout)

    注意
    :默认情况下,捕获的输出返回为bytes。如果要捕获为文本(例如str),请使用universal_newlines=True(或在Python>
    = 3.7上,使用无限清晰和易于理解的选项text=True-相同,universal_newlines但名称不同)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看