8

I have two small python files, the first reads a line using input and then prints another line

a = input()
print('complete')

The second attempts to run this as a subprocess

import subprocess

proc = subprocess.Popen('./simp.py',
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE,
                        bufsize=1)
print('writing')
proc.stdin.write(b'hey\n')
print('reading')
proc.stdout.readline()

The above script will print "writing" then "reading" but then hang. At first I thought this was a stdout buffering issue, so I changed bufsize=1 to bufsize=0, and this does fix the problem. However, it seems it's the stdin that's causing the problem.

With bufsize=1, if I add proc.stdin.flush() below the write, the process continues. Both of these approaches seem clumsy since (1) unbuffered streams are slow (2) adding flushes everywhere is error-prone. Why does the above write not flush on a newline? The docs say that bufsize is used when creating stdin, stdout, and stderr stream for the subprocess, so what's causing the write to not flush on the newline?

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • Curious indeed. `bufsize=1` works fine on python 2.x. – tdelaney Dec 19 '14 at 18:07
  • it is a [bug in Python 3](http://bugs.python.org/issue21332). It is fixed [for text mode](https://hg.python.org/cpython/rev/763d565e5840). See [subprocess line-buffering only works in universal newlines mode](http://bugs.python.org/issue21471) – jfs Dec 20 '14 at 09:12

1 Answers1

7

From the docs: "1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)". This works:

import subprocess

proc = subprocess.Popen('./simp.py',
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE,
                        bufsize=1,
                        universal_newlines=True)

print('writing')
proc.stdin.write('hey\n')
print('reading')
proc.stdout.readline()
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    It doesn't work in Python 3.4.1 and Python 3.4.2 (the current version) due to [the fix introduced by issue21396](http://bugs.python.org/issue21396). It is fixed in [issue21332](http://bugs.python.org/issue21332) (the quote from the docs is introduced by [the fix](https://hg.python.org/cpython/rev/763d565e5840)) – jfs Dec 20 '14 at 09:16