在python中将输出捕获为tty [英] Capture output as a tty in python

查看:119
本文介绍了在python中将输出捕获为tty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要tty的可执行文件(如stdin和stderr),并且希望能够对其进行测试. 我想输入标准输入,并捕获标准输出和标准错误的输出,这是一个示例脚本:

I have a executable which requires a tty (as stdin and stderr), and want to be able to test it. I want to input stdin, and capture the output of stdout and stderr, here's an example script:

# test.py
import sys
print("stdin: {}".format(sys.stdin.isatty()))
print("stdout: {}".format(sys.stdout.isatty()))
print("stderr: {}".format(sys.stderr.isatty()))
sys.stdout.flush()
line = sys.stdin.readline()
sys.stderr.write("read from stdin: {}".format(line))
sys.stderr.flush()

我可以在没有tty的情况下运行它,但是会被 .isatty 并返回False:

I can run this without tty, but that gets caught by .isatty and each return False:

import subprocess
p = subprocess.Popen(["python", "test.py"], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(b"abc\n")
print(p.communicate())
# (b'stdin: False\nstdout: False\nstderr: False\n', b'read from stdin: abc\n')

我想捕获stdout和stderr并让所有三个返回True-作为tty.

I want to capture the stdout and stderr and have all three return True - as a tty.

我可以使用 pty 来创建tty标准输入:

I can use pty to make a tty stdin:

import subprocess
m, s = pty.openpty()
p = subprocess.Popen(["python", "test.py"], stdin=s, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdin = os.fdopen(m, 'wb', 0)
os.close(s)
stdin.write(b"abc\n")
(stdout, stderr) = p.communicate()
stdin.close()
print((stdout, stderr))
# (b'stdin: True\nstdout: False\nstderr: False\n', b'read from stdin: abc\n')


我尝试了一堆排列以使stdout和stderr tty无效.
我想要的输出是:


I've tried a bunch of permutations to make stdout and stderr tty to no avail.
The output I want here is:

(b'stdin: True\nstdout: True\nstderr: True\n', b'read from stdin: abc\n')

推荐答案

下面的代码基于jfs的答案此处此处,以及您使用3个伪终端来区分stdout,stderr和stdin的想法(尽管请注意有一个加密警告可能出问题了(例如可能这样做会在OSX上截断stderr吗?).

The code below is based on jfs' answers here and here, plus your idea of using 3 pseudo-terminals to distinguish stdout, stderr and stdin (though note there is a cryptic warning that something may go wrong (such as a possibly truncated stderr on OSX?) by doing so).

还请注意,文档说pty仅适用于Linux 尽管它在其他平台上也可以工作":

Also note that the docs say pty is for Linux-only though it is "supposed to work" for other platforms:

import errno
import os
import pty
import select
import subprocess

def tty_capture(cmd, bytes_input):
    """Capture the output of cmd with bytes_input to stdin,
    with stdin, stdout and stderr as TTYs.

    Based on Andy Hayden's gist:
    https://gist.github.com/hayd/4f46a68fc697ba8888a7b517a414583e
    """
    mo, so = pty.openpty()  # provide tty to enable line-buffering
    me, se = pty.openpty()  
    mi, si = pty.openpty()  

    p = subprocess.Popen(
        cmd,
        bufsize=1, stdin=si, stdout=so, stderr=se, 
        close_fds=True)
    for fd in [so, se, si]:
        os.close(fd)
    os.write(mi, bytes_input)

    timeout = 0.04  # seconds
    readable = [mo, me]
    result = {mo: b'', me: b''}
    try:
        while readable:
            ready, _, _ = select.select(readable, [], [], timeout)
            for fd in ready:
                try:
                    data = os.read(fd, 512)
                except OSError as e:
                    if e.errno != errno.EIO:
                        raise
                    # EIO means EOF on some systems
                    readable.remove(fd)
                else:
                    if not data: # EOF
                        readable.remove(fd)
                    result[fd] += data

    finally:
        for fd in [mo, me, mi]:
            os.close(fd)
        if p.poll() is None:
            p.kill()
        p.wait()

    return result[mo], result[me]

out, err = tty_capture(["python", "test.py"], b"abc\n")
print((out, err))

收益

(b'stdin: True\r\nstdout: True\r\nstderr: True\r\n', b'read from stdin: abc\r\n')

这篇关于在python中将输出捕获为tty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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