-1

How can I print out the output of an external command by characters or at least by lines? This code prints it in one block after the command returns.

import subprocess as sub

output, errors = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True).communicate()
print output + errors
user2968409
  • 89
  • 1
  • 1
  • 4

2 Answers2

0

You can access to the standart output stream as

p = sub.Popen("cmd", stdout=sub.PIPE, stderr=sub.PIPE)

print(p.stdout.readline()) # This read a line

You can perform any operation o the file streams.

When you use readline in a standart output of a proccess the main thread of the app wait for that proccess to write some thing on the ouput. When that process write to the output you program continue.

You must know that before read a line from the proceess you need to call flush() on the stream. Because the streams have a cache time before the real values are written to it.

You can see this post, this is a good explanation of how this work on python

Community
  • 1
  • 1
chfumero
  • 1,067
  • 1
  • 13
  • 26
0

http://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/

import subprocess

p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
while True:
    out = p.stderr.read(1)
    if out == '' and p.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

It prints out the output of the cmd character by character.

user2968409
  • 89
  • 1
  • 1
  • 4