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.

6
  • 1
    You can perhaps print the output in var1, i.e. print(var1) Commented Oct 8, 2018 at 7:41
  • 1
    But real time does not happen right? Commented Oct 8, 2018 at 7:47
  • Perhaps you can stdout to a file then tail -f that file. Commented Oct 8, 2018 at 7:49
  • 1
    Possible duplicate of Getting realtime output using subprocess Commented Oct 8, 2018 at 7:53
  • That indeed does not happen realtime, only after the program has exited Commented Oct 8, 2018 at 7:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

just use this link https://stackoverflow.com/a/75175057/12780274 is very simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.