I have a simple script to mimic a program writing to stdout and stderr streams interleaved.
import sys
import time
for i in range(5):
print(int(time.time()), "This is Stdout")
print(int(time.time()), "Stderr", file=sys.stderr)
time.sleep(1)
When I run such a program with Python subprocess.Popen
I am loosing the order of stderr and stdout.
import subprocess
file = open('./stdout1.log', 'w', encoding='utf-8')
subprocess.Popen('./stderrout.py', stdout=file, stderr=file)
Output
1720517080 Stderr
1720517081 Stderr
1720517082 Stderr
1720517083 Stderr
1720517084 Stderr
1720517080 This is Stdout
1720517081 This is Stdout
1720517082 This is Stdout
1720517083 This is Stdout
1720517084 This is Stdout
I understand that the stderr gets flushed quicker or something of that sort, but how do I preserve the order?
I also tried using subprocess.STDOUT
for stderr and played with text
and bufsize
arguments with no luck. The output is identical in all cases
Here is the full program
import subprocess
file = open('./stdout1.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=file)
file = open('./stdout2.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=file, text=True, bufsize=0)
file = open('./stdout3.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=file, text=True, bufsize=1)
file = open('./stdout4.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=subprocess.STDOUT)
file = open('./stdout5.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=subprocess.STDOUT, text=True, bufsize=0)
file = open('./stdout6.log', 'w', encoding='utf-8') ; subprocess.Popen('./stderrout.py', stdout=file, stderr=subprocess.STDOUT, text=True, bufsize=1)
Is there a way to redirect both streams to the same file without losing the order?
If not what is the significance of bufsize
argument?