交互输入java_使用python进行交互式输入/输出

我有一个与用户交互的程序(就像一个shell),我想以交互方式使用python子进程模块运行它 . 这意味着,我希望有可能写入stdin并立即从stdout获取输出 . 我在这里尝试了许多解决方案,但它们似乎都不能满足我的需求 .

import Queue

import threading

import subprocess

def enqueue_output(out, queue):

for line in iter(out.readline, b''):

queue.put(line)

out.close()

def getOutput(outQueue):

outStr = ''

try:

while True: #Adds output from the Queue until it is empty

outStr+=outQueue.get_nowait()

except Queue.Empty:

return outStr

p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize = 1)

#p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True)

outQueue = Queue()

errQueue = Queue()

outThread = Thread(target=enqueue_output, args=(p.stdout, outQueue))

errThread = Thread(target=enqueue_output, args=(p.stderr, errQueue))

outThread.daemon = True

errThread.daemon = True

outThread.start()

errThread.start()

p.stdin.write("1\n")

p.stdin.flush()

errors = getOutput(errQueue)

output = getOutput(outQueue)

p.stdin.write("5\n")

p.stdin.flush()

erros = getOutput(errQueue)

output = getOutput(outQueue)

问题是队列保持为空,就好像没有输出一样 . 只有当我向stdin写入程序需要执行和终止的所有输入时,我才得到输出(这不是我想要的) . 例如,如果我做了类似的事情:

p.stdin.write("1\n5\n")

errors = getOutput(errQueue)

output = getOutput(outQueue)

有什么办法可以做我想做的事吗?

EDIT: 该脚本将在Linux机器上运行 . 我更改了我的脚本并删除了universal_newlines = True将bufsize设置为1并在wrtie之后立即刷新stdin . 我仍然没有输出 .

Second try: 我试过这个解决方案,它对我有用:

from subprocess import Popen, PIPE

fw = open("tmpout", "wb")

fr = open("tmpout", "r")

p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)

p.stdin.write("1\n")

out = fr.read()

p.stdin.write("5\n")

out = fr.read()

fw.close()

fr.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值