78

我正在寻找一种 Python 解决方案,它允许我将命令的输出保存在文件中,而不会将其隐藏在控制台中。

仅供参考:我问的是tee(作为 Unix 命令行实用程序),而不是 Python intertools 模块中同名的函数。

细节

  • Python解决方案(不调用tee,Windows下不可用)
  • 我不需要为被调用进程向标准输入提供任何输入
  • 我无法控制被调用的程序。我所知道的是它会输出一些东西到 stdout 和 stderr 并返回一个退出代码。
  • 调用外部程序(子进程)时工作
  • 为双方stderr工作stdout
  • 能够区分 stdout 和 stderr 因为我可能只想向控制台显示其中一个,或者我可以尝试使用不同的颜色输出 stderr - 这意味着这stderr = subprocess.STDOUT将不起作用。
  • 实时输出(渐进式) - 该过程可以运行很长时间,我无法等待它完成。
  • Python 3 兼容代码(重要)

参考

以下是我目前发现的一些不完整的解决方案:

图 http://blog.i18n.ro/wp-content/uploads/2010/06/Drawing_tee_py.png

当前代码(第二次尝试)

#!/usr/bin/python
from __future__ import print_function

import sys, os, time, subprocess, io, threading
cmd = "python -E test_output.py"

from threading import Thread
class StreamThread ( Thread ):
    def __init__(self, buffer):
        Thread.__init__(self)
        self.buffer = buffer
    def run ( self ):
        while 1:
            line = self.buffer.readline()
            print(line,end="")
            sys.stdout.flush()
            if line == '':
                break

proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutThread = StreamThread(io.TextIOWrapper(proc.stdout))
stderrThread = StreamThread(io.TextIOWrapper(proc.stderr))
stdoutThread.start()
stderrThread.start()
proc.communicate()
stdoutThread.join()
stderrThread.join()

print("--done--")

#### test_output.py ####

#!/usr/bin/python
from __future__ import print_function
import sys, os, time

for i in range(0, 10):
    if i%2:
        print("stderr %s" % i, file=sys.stderr)
    else:
        print("stdout %s" % i, file=sys.stdout)
    time.sleep(0.1)
实际输出
stderr 1
stdout 0
stderr 3
stdout 2
stderr 5
stdout 4
stderr 7
stdout 6
stderr 9
stdout 8
--done--

预期的输出是对行进行排序。备注,修改 Popen 以仅使用一个 PIPE 是不允许的,因为在现实生活中我会想用 stderr 和 stdout 做不同的事情。

同样,即使在第二种情况下,我也无法获得实时的输出,实际上所有结果都是在过程完成时收到的。默认情况下,Popen 不应该使用缓冲区(bufsize=0)。

4

6 回答 6

13

我看到这是一个相当古老的帖子,但以防万一有人仍在寻找一种方法来做到这一点:

proc = subprocess.Popen(["ping", "localhost"], 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.PIPE)

with open("logfile.txt", "w") as log_file:
  while proc.poll() is None:
     line = proc.stderr.readline()
     if line:
        print "err: " + line.strip()
        log_file.write(line)
     line = proc.stdout.readline()
     if line:
        print "out: " + line.strip()
        log_file.write(line)
于 2012-07-27T13:18:09.167 回答
8

如果需要 python 3.6 不是问题,那么现在有一种方法可以使用 asyncio。此方法允许您分别捕获 stdout 和 stderr,但仍将两者都流到 tty 而不使用线程。这是一个粗略的大纲:

class RunOutput():
    def __init__(self, returncode, stdout, stderr):
        self.returncode = returncode
        self.stdout = stdout
        self.stderr = stderr

async def _read_stream(stream, callback):
    while True:
        line = await stream.readline()
        if line:
            callback(line)
        else:
            break

async def _stream_subprocess(cmd, stdin=None, quiet=False, echo=False) -> RunOutput:
    if isWindows():
        platform_settings = {'env': os.environ}
    else:
        platform_settings = {'executable': '/bin/bash'}

    if echo:
        print(cmd)

    p = await asyncio.create_subprocess_shell(cmd,
                                              stdin=stdin,
                                              stdout=asyncio.subprocess.PIPE,
                                              stderr=asyncio.subprocess.PIPE,
                                              **platform_settings)
    out = []
    err = []

    def tee(line, sink, pipe, label=""):
        line = line.decode('utf-8').rstrip()
        sink.append(line)
        if not quiet:
            print(label, line, file=pipe)

    await asyncio.wait([
        _read_stream(p.stdout, lambda l: tee(l, out, sys.stdout)),
        _read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="ERR:")),
    ])

    return RunOutput(await p.wait(), out, err)


def run(cmd, stdin=None, quiet=False, echo=False) -> RunOutput:
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(
        _stream_subprocess(cmd, stdin=stdin, quiet=quiet, echo=echo)
    )

    return result

上面的代码基于这篇博文:https ://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/

于 2019-11-26T00:15:33.563 回答
7

这是teePython 的直接移植。

import sys
sinks = sys.argv[1:]
sinks = [open(sink, "w") for sink in sinks]
sinks.append(sys.stderr)
while True:
  input = sys.stdin.read(1024)
  if input:
    for sink in sinks:
      sink.write(input)
  else:
    break

我现在在 Linux 上运行,但这应该适用于大多数平台。


现在对于这一subprocess部分,我不知道您想如何将子进程的stdinstdoutstderr您的stdinstdoutstderr文件接收器“连接”,但我知道您可以这样做:

import subprocess
callee = subprocess.Popen( ["python", "-i"],
                           stdin = subprocess.PIPE,
                           stdout = subprocess.PIPE,
                           stderr = subprocess.PIPE
                         )

现在您可以像访问普通文件一样访问callee.stdin,callee.stdoutcallee.stderr启用上述“解决方案”。如果您想获得callee.returncode,则需要额外调用callee.poll().

写入时要小心callee.stdin:如果在您这样做时进程已经退出,则可能会出现错误(在 Linux 上,我明白了IOError: [Errno 32] Broken pipe)。

于 2010-06-08T13:09:44.213 回答
6

这是可以做到的

import sys
from subprocess import Popen, PIPE

with open('log.log', 'w') as log:
    proc = Popen(["ping", "google.com"], stdout=PIPE, encoding='utf-8')
    while proc.poll() is None:
        text = proc.stdout.readline() 
        log.write(text)
        sys.stdout.write(text)
于 2019-06-06T20:31:36.363 回答
1

如果您不想与流程交互,您可以使用 subprocess 模块就好了。

例子:

测试器.py

import os
import sys

for file in os.listdir('.'):
    print file

sys.stderr.write("Oh noes, a shrubbery!")
sys.stderr.flush()
sys.stderr.close()

测试.py

import subprocess

p = subprocess.Popen(['python', 'tester.py'], stdout=subprocess.PIPE,
                     stdin=subprocess.PIPE, stderr=subprocess.PIPE)

stdout, stderr = p.communicate()
print stdout, stderr

在您的情况下,您可以先简单地将 stdout/stderr 写入文件。您也可以通过通信向您的流程发送参数,尽管我无法弄清楚如何与子流程持续交互。

于 2010-06-08T13:36:11.717 回答
-1

我的解决方案并不优雅,但它确实有效。

您可以使用 powershell 在 WinOS 下访问“tee”。

import subprocess
import sys

cmd = ['powershell', 'ping', 'google.com', '|', 'tee', '-a', 'log.txt']

if 'darwin' in sys.platform:
    cmd.remove('powershell')

p = subprocess.Popen(cmd)
p.wait()
于 2019-06-05T20:34:37.577 回答