Can multiprocessing Process class be run from IDLE

空扰寡人 提交于 2019-11-26 07:49:02

问题


A basic example of multiprocessing Process class runs when executed from file, but not from IDLE. Why is that and can it be done?

from multiprocessing import Process

def f(name):
    print(\'hello\', name)

p = Process(target=f, args=(\'bob\',))
p.start()
p.join()

回答1:


Yes. The following works in that function f is run in a separate (third) process.

from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

However, to see the print output, at least on Windows, one must start IDLE from a console like so.

C:\Users\Terry>python -m idlelib
hello bob

(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.



来源:https://stackoverflow.com/questions/35293178/can-multiprocessing-process-class-be-run-from-idle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!