infiNity9819
infiNity9819

Reputation: 588

How to silence child Process stdout and stderr?

def f(x) :
    ....do something..
    ....many print statements....
    quit()

a = Process(target=f, args=1)
a.start()
....main process also has many print statement....

How to silence all print statements and error statements from the new spawned function f without silencing the stdout of main function? Furthermore, can I direct all the child outputs to a specific file live (i.e. without storing in a buffer then saving as the buffer can be lost if the program crashes)?

Upvotes: 1

Views: 266

Answers (1)

constt
constt

Reputation: 2320

I'd suggest to use redirect_stdout and redirect_stderr from the contextlib library in order to redirect all the output from the function running in a child process. First, make a decorator factory redirect_output that you then apply to your target functions passing a filename, where you want the stdout and stderr to be redirected to, as its parameter. Here is a complete working example:

#!/usr/bin/env python3
import sys
from functools import wraps
from contextlib import redirect_stdout, redirect_stderr
from multiprocessing import Process

def redirect_output(filename):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            with open(filename, 'w') as f:
                with redirect_stdout(f), redirect_stderr(f):
                    return func(*args, **kwargs)

        return wrapper

    return decorator

@redirect_output('worker.log')
def worker(*args, **kwargs):
    print(f'stdout: worker {args}, {kwargs}')
    print(f'stderr: worker {args}, {kwargs}', file=sys.stderr)

if __name__ == '__main__':
    proc = Process(target=worker, args=(1, 2), kwargs={'foo': 'bar'})
    proc.start()

Upvotes: 1

Related Questions