Python 2 to 3 conversion: iterating over lines in subprocess stdout -


i have following python 2 example code want make compatible python 3:

call = 'for in {1..5}; sleep 1; echo "hello $i"; done' p = subprocess.popen(call, stdout=subprocess.pipe, shell=true) line in iter(p.stdout.readline, ''):     print(line, end='') 

this works in python 2 in python 3 p.stdout not allow me specify encoding , reading return byte strings, rather unicode, comparison '' return false , iter won't stop. this issue seems imply in python 3.6 there'll way define encoding.

for now, have changed iter call stop when finds empty bytes string iter(p.stdout.readline, b''), seems work in 2 , 3. questions are: safe in both 2 , 3? there better way of ensuring compatibility?

note: i'm not using for line in p.stdout: because need each line printed it's generated , according this answer p.stdout has large buffer.

you can add unversal_newlines=true.

p = subprocess.popen(call, stdout=subprocess.pipe, shell=true, universal_newlines=true) line in iter(p.stdout.readline, ''):     print(line, end='') 

instead of bytes, str returned '' work in both situations.

here docs have option:

if universal_newlines false file objects stdin, stdout , stderr opened binary streams, , no line ending conversion done.

if universal_newlines true, these file objects opened text streams in universal newlines mode using encoding returned locale.getpreferredencoding(false). stdin, line ending characters '\n' in input converted default line separator os.linesep. stdout , stderr, line endings in output converted '\n'. more information see documentation of io.textiowrapper class when newline argument constructor none.

it's not explicitly called out bytes versus str difference, implied stating false returns binary stream , true returns text stream.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -