Search code examples
pythonsubprocessstdoutpopenreadline

Read stdout from subprocess until there is nothing left


I would like to run several commands in the same shell. After some research I found that I could keep a shell open using the return process from Popen. I can then write and read to stdin and stdout. I tried implementing it as such:

process = Popen(['/bin/sh'], stdin=PIPE, stdout=PIPE)
process.stdin.write('ls -al\n')
out = ' '
while not out == '':
    out = process.stdout.readline().rstrip('\n')
    print out

Not only is my solution ugly, it doesn't work. out is never empty because it hands on the readline(). How can I successfully end the while loop when there is nothing left to read?


Solution

  • Use iter to read data in real time:

    for line in iter(process.stdout.readline,""):
       print line
    

    If you just want to write to stdin and get the output you can use communicate to make the process end:

    process = Popen(['/bin/sh'], stdin=PIPE, stdout=PIPE)
    out,err =process.communicate('ls -al\n')
    

    Or simply get the output use check_output:

    from subprocess import check_output
    
    out = check_output(["ls", "-al"])