Python 同步 stdout 和 stderr 输出

Loo*_*bon 7 printing stdout stderr python-3.x

使用以下代码:

import sys

print("INFO", flush=True, file=sys.stdout)
print("ERROR", flush=True, file=sys.stderr)
Run Code Online (Sandbox Code Playgroud)

有时输出是:

ERROR
INFO
Run Code Online (Sandbox Code Playgroud)

有时

INFO
ERROR
Run Code Online (Sandbox Code Playgroud)

如何才能让它始终按照代码中编写的顺序打印呢?

小智 -1

The order in which you write the statements in your code does not guarantee the order in which they will be printed. This is because stdout and stderr are two different streams and the order in which they're written to can be affected by various factors such as buffering and output device performance.

If you want to ensure that the output is always printed in a specific order, you can use a lock or mutex to synchronise access to the streams. This will ensure that only one thread can write to the streams at a time, so the output will be printed in the order that the threads acquire the lock. Using your code as an example, give this a try -

import threading
import sys

lock = threading.Lock()

def print_info():
    with lock:
        print("INFO", flush=True, file=sys.stdout)

def print_error():
    with lock:
        print("ERROR", flush=True, file=sys.stderr)

print_info()
print_error()
Run Code Online (Sandbox Code Playgroud)