使用Python的交互式输入输出

使用Python的交互式输入输出,第1张

使用Python的交互式输入/输出

在Linux上针对此问题的两种解决方案:

第一个是使用文件将输出写入其中,并同时读取输出:

from subprocess import Popen, PIPEfw = open("tmpout", "wb")fr = open("tmpout", "r")p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)p.stdin.write("1n")out = fr.read()p.stdin.write("5n")out = fr.read()fw.close()fr.close()

第二,正如JF Sebastian提供的那样,是使用fnctl模块使p.stdout和p.stderr管道不阻塞

import osimport fcntlfrom subprocess import Popen, PIPE  def setNonBlocking(fd):    """    Set the file description of the given file descriptor to non-blocking.    """    flags = fcntl.fcntl(fd, fcntl.F_GETFL)    flags = flags | os.O_NonBLOCK    fcntl.fcntl(fd, fcntl.F_SETFL, flags)p = Popen("./a.out", stdin = PIPE, stdout = PIPE, stderr = PIPE, bufsize = 1)setNonBlocking(p.stdout)setNonBlocking(p.stderr)p.stdin.write("1n")while True:    try:        out1 = p.stdout.read()    except IOError:        continue    else:        breakout1 = p.stdout.read()p.stdin.write("5n")while True:    try:        out2 = p.stdout.read()    except IOError:        continue    else:        break


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5662009.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存