如何解决仅在 Python subprocess.Popen.communicate 中发送 stdin 后才获取 stdout
我正在尝试使用 Python 中的 subprocess
模块编写一些简单的测试。被测试的程序很简单:
def main():
x = int(input("Integer? "))
print('Output is',x // 12)
main()
def test_output():
ret = subprocess.Popen(args=['python3',FILENAME],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output,err = ret.communicate(b"216\n")
print(f"Output: {output}")
然而,output
正在捕获来自目标程序的 input
调用的提示以及随后的标准输出:
Output: b'Integer? Output is 18\n'
我怎样才能只获得 Output is 18\n'
部分?我不在乎 input()
解决方法
更糟糕的方法:等待提示
这里,我们在阻塞模式下读取一个字节(延迟到打印提示),然后在切换回来之前消耗所有准备好的并等待读取在非阻塞模式到阻塞模式。
#!/usr/bin/env python3
from select import select
import fcntl
import subprocess
import threading
import os
import sys
def test_output(timeout=0.1):
ret = subprocess.Popen(args=['python3','testsubject.py'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize=0)
# you probably want to replace this with a function that _stores_ stderr
stderr_reader = threading.Thread(target = ret.stderr.read)
stderr_reader.start()
# wait until the prompt has been at least partially written
prompt_start = ret.stdout.read(1)
# go into nonblocking mode
orig_flags = fcntl.fcntl(ret.stdout,fcntl.F_GETFL)
fcntl.fcntl(ret.stdout,fcntl.F_SETFL,orig_flags | os.O_NONBLOCK)
# read further output until there's nothing left
prompt_rest = ret.stdout.read()
print(f"Skipping prompt: {prompt_start.decode('utf-8')}{prompt_rest.decode('utf-8')}",file=sys.stderr)
# exit nonblocking mode
fcntl.fcntl(ret.stdout,orig_flags)
# write to stdin
ret.stdin.write(b'216\n')
ret.stdin.close()
output = ret.stdout.read()
print(f"Output: {output.decode('utf-8')}")
test_output()
更好的方法:修复被测程序
这里出错的组件是作为子进程调用的程序,而不是调用子进程的程序。有两种主要的修复方法:
-
当不是由用户交互运行时,不要打印提示。
def main(): x = int(input("Integer? " if os.isatty(0) else None)) print('Output is',x // 12) main()
这是有效的,因为当程序使用
os.isatty(0)
运行时stdin=subprocess.PIPE
为假。 -
将提示打印到 stderr,而不是 stdout,因此它与“诊断日志”(“准备好输入”是诊断状态的示例)而不是输出分开。
def main(): sys.stderr.write("Integer? ") x = int(input()) print('Output is',x // 12) main()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。