使用多处理的过程无输出 [英] No output from Process using multiprocessing
问题描述
我是多处理领域的初学者,谁能告诉我为什么它不产生任何输出?
I am a beginner in multiprocessing, can anyone tell me why this does not produce any output?
import multiprocessing
def worker(num):
"""thread worker function"""
print('Worker:', num)
if __name__ == '__main__':
jobs = []
for i in range(4):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
推荐答案
您正在启动Process()
,但是从不等待它完成,因此您的程序的执行在后台进程完成之前结束.通过调用 Process.join()
来尝试此操作:
You're starting your Process()
, but never waiting on it to complete, so your program's execution ends before the background process finishes. Try this, with a call to Process.join()
:
import multiprocessing
import sys
def worker(num):
"""thread worker function"""
print('Worker:', num)
sys.stdout.flush()
if __name__ == '__main__':
jobs = []
for i in range(4):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
map(lambda p: p.join(), jobs)
在这里,我们使用 map()
来调用join()
在jobs
列表中的每个进程上.
Here we use map()
to call join()
on each process in the jobs
list.
这是此工作的一个示例:
Here's an example of this working:
In [127]: %paste
import multiprocessing
import sys
def worker(num):
"""thread worker function"""
print('Worker:', num)
sys.stdout.flush()
if __name__ == '__main__':
jobs = []
for i in range(4):
p = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p)
p.start()
map(lambda p: p.join(), jobs)
## -- End pasted text --
Worker: 2
Worker: 1
Worker: 0
Worker: 3
In [128]:
关于为什么它在IDLE中不起作用,请参见此答案:
As for why this isn't working in IDLE, see this answer:
但是,要查看
However, to see the
C:\Users\Terry>python -m idlelib
hello bob
(在2.x上使用idlelib.idle
.)原因是IDLE在单独的进程中运行用户代码.当前,IDLE进程和用户代码进程之间的连接是通过套接字进行的.通过多处理完成的派生不会复制或继承套接字连接.通过图标或资源管理器启动IDLE(在Windows中)时,打印输出无处可去.从具有python
(而不是pythonw
)的控制台启动时,输出将如上所述进入控制台.
(Use idlelib.idle
on 2.x.) The reason is that IDLE runs user code in a separate process. Currently the connection between the IDLE process and the user code process is via a socket. The fork done by multiprocessing does not duplicate or inherit the socket connection. When IDLE is started via an icon or Explorer (in Windows), there is nowhere for the print output to go. When started from a console with python
(rather than pythonw
), output goes to the console, as above.
这篇关于使用多处理的过程无输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!