简体   繁体   中英

Python subprocess readlines()?

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()
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

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()

进行系统调用,将 stdout 输出作为字符串返回

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

直接从help(subprocess)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM