0

I have to get command output to variable in python.

I am using python subprocess

from subprocess import *
var1 = check_output(["some_command"]) 

Above Command successfully loads command output to variable var1

I want to see real time output on to the terminal. I can use call like below

 call(["some command"]) 

Now i want to achieve two things at same time that is, load output to variable and display output to terminal. Please help me.

Dev Ops Ranga
  • 203
  • 6
  • 15

1 Answers1

0

I think this will work, for line-based real-time output:

proc = subprocess.Popen(["some_command"], stdout=subprocess.PIPE)
var1 = []
while True:
    line = proc.stdout.readline()
    if not line:
        break
    var1.append(line)
    sys.stdout.write(line)
var1 = "".join(var1)

The iterator version of readline (for line in proc.stdout) does not work here because it performs too much buffering. You could also use proc.stdout.read(1) instead of readline() to completely disable buffering.

Note that this will not port well to Python 3 because sys.stdout is text-oriented (uses Unicode), but processes are byte-oriented (although the latter can be changed in recent Python 3 versions).

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92