Python Process() Output: How to Capture Child Process Output in Main Process
When using the 'Process()' function in Python, the output of the child process is not automatically sent to the main process. This is because the child process runs independently of the main process and has its own standard output (stdout) and standard error (stderr) streams.
To capture the output of the child process in the main process, you need to use a communication mechanism such as pipes or queues. Here's an example using a 'Queue':
import multiprocessing
def worker(q):
print('Child process')
q.put('Hello from child')
if __name__ == '__main__':
q = multiprocessing.Queue()
p = multiprocessing.Process(target=worker, args=(q,))
p.start()
p.join()
print('Main process')
while not q.empty():
print(q.get())
In this example, the child process writes a message to the queue using 'q.put()'. The main process waits for the child process to finish using 'p.join()' and then reads from the queue using 'q.get()'. The output should be:
Child process
Main process
Hello from child
原文地址: https://www.cveoy.top/t/topic/nAHX 著作权归作者所有。请勿转载和采集!