13
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

概要

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
(以下略)

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

13
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?