Search code examples
pythonpython-3.xstdoutpython-multiprocessing

Change a redirect_stdout context


For context, I'm using multiprocessing and running several child processes, which may print on stdout the logs of what they are doing. Since they may print at the same time, resulting in very messy logs, I'm using a

from contextlib import redirect_stdout

for task in task_list:
    with redirect_stdout(buffer):
        (do some stuff)
    with lock_stdout:
        print(buffer)

structure. This way, they only print after they have finished a task, and this works fine. Now, under some particular conditions, I want to be able to print something on stdout inside this context marked with "(do some stuff)", but the only way I have been able to print anything to stdout is through the use of warnings, which is very dirty. Is there an elegant way to redirect stdtout back to stdout for a while?


Solution

  • You can store sys.stdout into a variable (possibly a global) before you run your "stuff", and use print("stuff", file=real_stdout)