Alex.JvV
Alex.JvV

Reputation: 59

Popen multi line read

I'm pretty new to python I have been using popen to execute commands but I am expecting a multiple line response and I need to use each line separately.

I have the following code that I got from a tutorial.

pipe = os.popen('dir')
        for line in pipe:
            print '--------------space---------------------'
            print pipe.readLine()

but know I keep getting the following error:

AttributeError: 'file' object has no attribute 'readLine'

does anyone have any advice for me, or an idea of how to rather improve this.

thanks for any help

Upvotes: 0

Views: 2990

Answers (2)

Mark Beilfuss
Mark Beilfuss

Reputation: 602

To fix your syntax readline uses a lower case l.

However I'd like to know what you're trying to accomplish. If you just want to print each line then you should just change print pipe.readline() --> print line.

import os
pipe = os.popen('dir')
for line in pipe:
    print '--------------space---------------------'
    print line

Your for loop is already reading the output line by line from popen. In fact if you attempt to call pipe.readline() mid-iteration it is illegal and your code will raise an exception.

To illustrate the exception you can try running this:

import os
pipe = os.popen('dir')
for line in pipe:
    print '--------------space---------------------'
    print pipe.readline()

Upvotes: 1

Bob Ezuba
Bob Ezuba

Reputation: 510

Use subprocess module, it has a lot of useful functions to interact with other processes. check_output or call will do the job

import subprocess
output = subprocess.check_output('dir', universal_newlines=True)

Upvotes: 1

Related Questions