46

ユーザーと対話する (シェルのように動作する) プログラムがあり、Python サブプロセス モジュールを使用して対話的に実行したいと考えています。つまり、標準入力に書き込み、すぐに標準出力から出力を取得する可能性が必要です。ここで提供されている多くのソリューションを試しましたが、どれも私のニーズに合っていないようです。

私が書いたコードは、Running an interactive command from within 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

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)

問題は、あたかも出力がないかのように、キューが空のままであることです。プログラムが実行して終了する必要があるすべての入力を標準入力に書き込んだ場合にのみ、出力が得られます(これは私が望んでいるものではありません)。たとえば、次のようなことをするとします。

p.stdin.write("1\n5\n")
errors = getOutput(errQueue)
output = getOutput(outQueue)

私がやりたいことをする方法はありますか?


スクリプトは Linux マシンで実行されます。スクリプトを変更し、universal_newlines=True を削除し、bufsize を 1 に設定し、書き込み直後に標準入力をフラッシュしました。それでも出力が得られません。

2 回目の試行:

私はこの解決策を試しましたが、うまくいきました:

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()
4

4 に答える 4