简体   繁体   中英

Python subprocess to get real output and load output to variable

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.

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

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