2012/01/21

python read subprocess stdout line by line


proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline,''):
    print line

でまわす.

for line in proc.stdout:

ではうまくいかない

参考:
http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line


追記:

hoge.sh | python foo.py

みたいな形で,パイプからの入力を標準入力で受ける場合も同じ.
CSV形式で読むならこんな感じ

csvreader = csv.reader(iter(sys.stdin.readline, ''))
for data_vals in csvreader:
    print data_vals

参考:
http://stackoverflow.com/questions/6556078/how-to-read-a-csv-file-from-a-stream-and-process-each-line-as-it-is-written

0 件のコメント: