I have a Python script that executes two main tasks:
- Execute code from the script itself
- Launch a background process with
multiprocessing.Process(target=...)
My question is: Is there any way of muting the stdout
from that particular process without affecting the main process? I've tried to change it through sys.stdout
, but it affects every single process and the main process (every instance of the program points to the same object):
>>> import multiprocessing
>>> import sys
>>> def a():
... print('{} - {}'.format(sys.stdout, id(sys.stdout)))
...
>>> for i in range(5):
... multiprocessing.Process(target=a).start()
...
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
>>> <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
>>> a()
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
It is not possible to delete all print()
statements from the function being executed by the process, since another routine of the program calls that function on the main process and it needs those print statements.
I also noticed that I could use a boolean flag to indicate whether the print should be executed or not, but I was hoping that anyone could give me a better approach.
Thank you very much!