Why does the first loop go wrong with Python3

Cecil Westerhof Cecil at decebal.nl
Tue May 19 08:24:45 EDT 2015


I have the following code:
    from __future__     import division, print_function

    import subprocess

    p = subprocess.Popen('ls -l', shell = True, stdout = subprocess.PIPE)
    for line in iter(p.stdout.readline, ''):
        print(line.rstrip().decode('utf-8'))

    p = subprocess.Popen('ls -l', shell = True, stdout = subprocess.PIPE)
    for line in p.stdout.readlines():
        print(line.rstrip().decode('utf-8'))

This works in Python2. (Both give the same output.)

But when I execute this in Python3, then the first loop is stuck in a
loop where it continually prints a empty string. The second loop is
executed correctly in Python3.

In the current case it is not a problem for me, but when the output
becomes big, the second solution will need more memory. How can I get
the first version working in Python3?

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list