Python subprocess readlines()?

2019-02-08 11:51发布

问题:

So I'm trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I'm having is I can't seem to find a way of making readlines() work.

So I used to be able to do

list = os.popen('ls -l').readlines()

But I can't do

list = subprocess.Popen(['ls','-l']).readlines()

回答1:

With subprocess.Popen, use communicate to read and write data:

out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() 

Then you can always split the string from the processes' stdout with splitlines().

out = out.splitlines()


回答2:

ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.stdout.readlines()

or, if you want to read line-by-line (maybe the other process is more intensive than ls):

for ln in ls.stdout:
    # whatever


回答3:

Making a system call that returns the stdout output as a string:

lines = subprocess.check_output(['ls', '-l']).splitlines()


回答4:

list = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0].splitlines()

straight from the help(subprocess)



回答5:

A more detailed way of using subprocess.

        # Set the command
        command = "ls -l"

        # Setup the module object
        proc = subprocess.Popen(command,
                            shell=True,   
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

        # Communicate the command   
        stdout_value,stderr_value = proc.communicate()

        # Once you have a valid response, split the return output    
        if stdout_value:
            stdout_value = stdout_value.split()