小编Tal*_*ich的帖子

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

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

我编写的代码基于在python中运行交互式命令

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 …
Run Code Online (Sandbox Code Playgroud)

python stdin subprocess interactive stdout

29
推荐指数
3
解决办法
3万
查看次数

标签 统计

interactive ×1

python ×1

stdin ×1

stdout ×1

subprocess ×1