Help us understand the problem. What is going on with this article?

Pythonでサブプロセスの標準出力を1行ずつ読み込む

More than 5 years have passed since last update.

概要

subprocessモジュールを使って子プロセスを作ることはあるかと思いますが,例えばそいつのログを監視するみたいなことをしたくなることがあると思うので,メモ.

子プロセス

0.5秒ごとに数字を標準出力します.

child.py
import time
import sys
i = 0
while True:
   print i
   sys.stdout.flush()
   i += 1
   time.sleep(0.5)

ポイントはflush()してバッファに溜まったデータを吐き出すところです.

親プロセス

子が出力したらその都度出力します.

parent.py
import subprocess
proc = subprocess.Popen(['python','child.py'],stdout=subprocess.PIPE)

print "ready"
for line in iter(proc.stdout.readline,''):
   print line

結果

ready
1
2
3
4
5
(以下略)

子プロセスから読み込む部分はスレッドを作って非同期で読み込んでデータをキューに入れるとかしたら色々できそうです.

xeno14
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした