Writing to open subprocess pipes.

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 16 17:27:55 EDT 2010


On Wed, Jun 16, 2010 at 2:29 PM, Brandon McGinty
<brandon.mcginty at gmail.com> wrote:
> Both subprocess and os.popen* only allow inputput and output one time, and
> the output to be read only when the process terminates.

You can read output before the subprocess terminates by setting the
pipe to be non-blocking:

import fcntl
import os
import subprocess

>>> process = subprocess.Popen("cat", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>>> flags = fcntl.fcntl(process.stdout, fcntl.F_GETFL)
>>> fcntl.fcntl(process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
0
>>> process.stdin.write('line1\n')
>>> process.stdout.read()
'line1\n'
>>> process.stdin.write('line2\n')
>>> process.stdout.read()
'line2\n'

Cheers,
Ian



More information about the Python-list mailing list