I have the following Python 2 example code that I want to make compatible with Python 3:
call = 'for i in {1..5}; do sleep 1; echo "Hello $i"; done'
p = subprocess.Popen(call, stdout=subprocess.PIPE, shell=True)
for line in iter(p.stdout.readline, ''):
print(line, end='')
This works well in Python 2 but in Python 3 p.stdout
does not allow me to specify an encoding and reading it will return byte strings, rather than Unicode, so the comparison with ''
will always return false and iter
won't stop. This issue seems to imply that in Python 3.6 there'll be a way to define this encoding.
For now, I have changed the iter
call to stop when it finds an empty bytes string iter(p.stdout.readline, b'')
, which seems to work in 2 and 3. My questions are: Is this safe in both 2 and 3? Is there a better way of ensuring compatibility?
Note: I'm not using for line in p.stdout:
because I need each line to be printed as it's generated and according to this answer p.stdout
has a too large a buffer.