Is it just my environment?
In a Python script, when the standard (error) output is converted to a file or executed from another Python script, the output timing is incorrect. It comes out at once when the process ends, not when print or sys.stdout.write is executed.
This is the executed Python script. Just give a number every second.
child1.py
from time import sleep
for i in range(10):
print(str(i))
sleep(1)
When this is executed with the following command, nothing is output and a log is output at once after 10 seconds have passed.
$ python3 ./child1.py > stdout.log & tail -f stdout.log
Next is the modified version. Try running sys.stdout.flush after print.
child2.py
from time import sleep
import sys
for i in range(10):
print(str(i))
sys.stdout.flush()
sleep(1)
Similarly, if you execute the following command, it will be output every second.
$ python3 ./child2.py > stdout.log & tail -f stdout.log
By the way,
$ python3 ./child1.py
And, there is no problem in outputting to the screen.
As the parent script, I used the one posted in here.
parent.py
import sys
import subprocess
def get_lines(cmd):
'''
:param cmd:str command to execute.
:rtype: generator
:return:Standard output(Line by line).
'''
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
line = proc.stdout.readline()
if line:
yield line.decode('utf-8')
if not line and proc.poll() is not None:
break
if __name__ == '__main__':
for line in get_lines(cmd='python3 ./child1.py'): # ./child2.When I run py, it is output every second
sys.stdout.write(line)
With this, even when outputting to the screen, child1.py is output at once after 10 seconds, and child2.py is output every second.
Is it such a thing? → Such a thing.
(Addition) As pointed out in the comment below, it was confirmed that if you add the -u option when executing the python3 command, it will be output at any time. I've become smarter again. \ # I'll try to write the "I couldn't do it" system.
Recommended Posts