Search code examples
python-3.xmultiprocessingpython-multiprocessing

Python start multiprocessing without print/logging statements from processes


I am starting two processes via multiprocessing and this is working fine. The only problems which I have are the print and debug statements from these two processes.

The hope is, to use the REPL and start the processes, like in the background. However, I do not get this to run. I always get the debug statements and therefore can't use the REPL anymore. This is how I call the processes:

processes = [
    Process(target=start_viewer, args=()),
    Process(target=start_server, args=(live, amount, fg))
] 

for p in processes:
    p.start()

Any idea on how to "mute" the process, or get them in the background?


Solution

  • If I correct understand you, you want to not show printing from one of processes. You can achieve this by redirect output of the Python Interpreter. Add sys.stdout = open("/dev/null", 'w') to the process which you want to "mute".

    Full working example below.

    from multiprocessing import Process
    from time import sleep
    import sys
    
    
    def start_viewer():
        sys.stdout = open("/dev/null", 'w')
        while True:
            print("start_viewer")
            sleep(1)
    
    def start_server():
        while True:
            print("start_server")
            sleep(1)
    
    if __name__ == '__main__':
        processes = [
            Process(target=start_viewer, args=()),
            Process(target=start_server, args=())
        ]
    
        for p in processes:
            p.start()
    

    Be aware that /dev/null is like passing prints to nowhere, if you want to save it you can use text file. Also to achieve multi os support you should use os.devnull.