Python のサブプロセス PIPE での非ブロッキング読み取り 質問する

Python のサブプロセス PIPE での非ブロッキング読み取り 質問する

私はサブプロセスモジュールサブプロセスを開始し、その出力ストリーム (標準出力) に接続します。その標準出力で非ブロッキング読み取りを実行できるようにしたいと考えています。 .readline を非ブロッキングにする方法、または呼び出す前にストリームにデータがあるかどうかを確認する方法はありますか.readline? これを移植可能にするか、少なくとも Windows と Linux で動作するようにしたいと思います。

現時点では、次のように実行します (.readlineデータが利用できない場合はブロックします)。

p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()

ベストアンサー1

fcntlselectasyncprocこの場合は役に立ちません。

オペレーティングシステムに関係なく、ブロックせずにストリームを読み取る信頼性の高い方法は、Queue.get_nowait():

import sys
from subprocess import PIPE, Popen
from threading  import Thread

try:
    from queue import Queue, Empty
except ImportError:
    from Queue import Queue, Empty  # python 2.x

ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()

p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()

# ... do other things here

# read line without blocking
try:  line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
    print('no output yet')
else: # got line
    # ... do something with line

おすすめ記事