问题:python多进程,子函数内容没有打印出来。
Simple Python Multiprocessing function doesn't output results
I have this very simple function right here in which I'm trying to run and test on, however, it doesn't output anything and it doesn't have any errors either. I've checked the code multiple times but it doesn't have any errors.
I printed jobs and here's what I got:
[,,,,]
Here's the code:
importmultiprocessingdefworker(num):print"worker ",numreturnjobs=[]foriinrange(5):p=multiprocessing.Process(target=worker,args=(i,))jobs.append(p)p.start()
Here's the result I'm expecting but it's not outputting anything:
Worker:0Worker:1Worker:2Worker:3Worker:4
原因:spyder使用的stdout和windows不支持forking,所以无法打印子进程内容。
The comments revealed that OP uses Windows as well as Spyder. Since Spyder redirectsstdoutand Windows does not supportforking, a new child process won't print into the Spyder console. This is simply due to the fact thatstdoutof the new child process is Python's vanilla stdout, which can also be found insys.__stdout__.
解决:1.打印日志到文件。2.用返回值替代打印。
There are two alternatives:
Using the logging module. This would encompass creating and logging all messages to one or several files. Using a single log-file may lead to the problem that the output is slightly garbled since the processes would write concurrently to the file. Using a single file per process could solve this.
Not using print within the child processes, but simply returning the result to the main process. Either by using a queue (or multiprocessing.Manager().Queue() since forking is not possible) or more simply by relying on the multiprocessing Pool's map functionality, see example below.
Multiprocessing example with a Pool:
importmultiprocessingdefworker(num):"""Returns the string of interest"""return"worker %d"%numdefmain():pool=multiprocessing.Pool(4)results=pool.map(worker,range(10))pool.close()pool.join()forresultinresults:# prints the result string in the main processprint(result)if__name__=='__main__':# Better protect your main function when you use multiprocessingmain()
which prints (in the main process)
worker0worker1worker2worker3worker4worker5worker6worker7worker8worker9
EDIT: If you are to impatient to wait for the map function to finish, you can immediately print your results by using imap_unordered and slightly changing the order of the commands:
defmain():pool=multiprocessing.Pool(4)results=pool.imap_unordered(worker,range(10))forresultinresults:# prints the result string in the main process as soon as say are ready# but results are now no longer in order!print(result)# The pool should join after printing all resultspool.close()pool.join()来源:https://stackoverflow.com/questions/29629103/simple-python-multiprocessing-function-doesnt-output-results/29632397#29632397