Read the output of the script in real time through subprocess

I want to get the output of the script in real time through subprocess
here is my script

< H2 > test_echo.py < / H2 >

import time
for i in range (10):

print(i)
time.sleep(0.5)
< hr >

here is the read script:

< H2 > script name get_output.py < / H2 >

import subprocess

cmd ="/ root/test_echo.py"
p = subprocess.Popen (["python",cmd], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,bufsize=1)
while 1:

line = p.stdout.readline()
if line != "" and p.poll() is None:
    print line
else:
    break
< hr >

I debug the above content with pycharm and can normally read the contents of test_echo line by line (real-time). However, when I put the script on centos or mac under the shell environment, it cannot be read line by line through python get_output.py. Instead, I want to know how to read line by line in the terminal as in pycharm, or how to configure subprocess

when the result of test_echo.py is finished. I want to know how to read it line by line as in pycharm.
Mar.28,2021

solution A:

try changing your test_echo.py like this:

import sys
import time
for i in range(10):

    print(i)
    sys.stdout.flush()
    time.sleep(0.5)

solution B:

use PYTHONUNBUFFERED=1 python get_output.py

when executing The reason for the

problem is that everything output in stdout in python is actually put into buffer first. Pycharm will automatically flush, after each print, while normal python will not in bash. So either you can manually flush it yourself, or tell python that I don't want buffer to output directly.


if there is also output in the executed script, you also want to display the output in real time. If the stdout cache is removed, you can add PYTHONUNBUFFERED=1 python get_output.py, before the execution of the script or use p = subprocess.Popen (['python', "- u",' get_output.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,bufsize=1), python-u and PYTHONUNBUFFERED=1 have the same effect. Very 6 A small function of real-time web applications has been successful

Menu