【问题标题】:Capture the output of ONLY stdout in python在 python 中捕获 ONLY 标准输出的输出
【发布时间】:2019-07-22 06:11:41
【问题描述】:

PYTHON 版本 - 3.5.2 操作系统 - Ubuntu 16.04 LTS

我目前正在使用 stdout 和 print 语句来写入终端。 我想捕获 ONLY sys.stdout.write 命令的输出,而不是打印命令 因此,例如,如果我的代码是 -

import sys
sys.stdout.write("Hello")
print("PRINT")

我只想捕获“Hello”而不是“PRINT”。

我目前正在使用这个:

x = subprocess.run(['python3 test.py'] , shell = True , stdout = subprocess.PIPE).stdout.decode('utf-8')

这给了我这个输出:

['HelloPRINT', '']

【问题讨论】:

  • print() 使用sys.stdout.write() 来显示文本。但是 suproccess 只看到系统发送的文本,它不知道您使用什么向系统发送文本。
  • print 默认写入sys.stdout。但是,您可以在 print 函数的 file 参数中覆盖此行为。
  • 您只能将print() 重定向到文件或stderr 但您必须在代码print("Print", file=sys.stderr) 中执行此操作
  • 那么当我将它重定向到sys.stderr 时,文本会发生什么?
  • 当您在控制台/终端中运行它时,您将看到所有文本 - stdout` 和 stderr - 但子进程将仅获得 stdout,因为您仅设置了 stdout = subprocess.PIPE

标签: python python-3.x stdout


【解决方案1】:

print() 使用sys.stdout.write() 来显示文本。

除了suproccess 只看到系统发送的文本,它不知道你用什么发送文本到系统。

您只能在代码中将print() 重定向到sys.stderr

import sys
sys.stdout.write("Hello")
print("PRINT", file=sys.stderr)

然后当你在控制台中运行时你仍然会看到所有文本,但是当你使用subprocess 时你只会得到sys.stdout

如果您在控制台中使用,您也只会在文件中获得stdout

python script.py > stdout.txt

或者你重定向到其他程序

python script.py | sort

您也可以使用sys.stderr.write("PRINT\n") 代替print(... ,file=sys.stderr),但您必须在末尾手动添加"\n"

【讨论】:

    【解决方案2】:

    您不能这样做,因为print() 在内部使用sys.stdout.write()。以下 REPL 会话说明了这一点:

    >>> import sys
    >>> class StdoutProxy:
    ...  def write(self, text):
    ...   return len(text) # do nothing
    ...
    >>> sys.stdout = StdoutProxy()
    >>> print("Hello!")
    >>> sys.stdout = sys.__stdout__  # reset stdout to its original state
    >>> print("Hello!")
    Hello!
    

    【讨论】:

    • 我将 print 的输出重定向到 sys.stderr。这解决了我的目的。
    【解决方案3】:

    您可以像这样定义自己的print 函数版本:

    import sys
    
    def get_my_print(file=sys.stdout):
        _original_print = print
        def my_print(*objects, sep='', end='\n', file=file, flush=False):
            _original_print(*objects, sep='', end='\n', file=file, flush=False)
        return my_print
    
    original_print = print
    print("Redirect print to stderr...")
    print = get_my_print(sys.stderr)
    
    print("Print some numbers...")
    for x in range(10):
        print(x)
    
    print = original_print
    print("Done.")
    

    控制台

    $ python3 redirect_print.py 1> /dev/null
    Print some numbers...
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多