LoginSignup
1
4

More than 5 years have passed since last update.

Python3でサブプロセスを起動してサーバ的に使う

Posted at

Pythonではsubprocessモジュールを使うとサブプロセスを起動できます。そのサブプロセスにデータを入力し、処理結果をもらいたい場合があります。それもサブプロセスを終わらせず、サーバー的に使いたい。

client.py
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import sys

p = Popen(['cat'], bufsize=0, stdin = PIPE, stdout = PIPE)
while True:
    s = sys.stdin.readline()
    p.stdin.write(s.encode('utf-8'))
    output = p.stdout.readline()
    print(output.decode('utf-8'), end='')

Popenの引数のbufsitze=0がキモです。また、起動されるサブプロセス(この場合はcat)の出力はバッッファリングしない(出力ごとにflushする)必要があります。ソースがなくて改造できないコマンドでも、出力をバッファリングしないオプションがある場合がありますので、確かめてください。

1
4
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
1
4