Can multiprocessing Process class be run from IDLE

前端 未结 1 1157
死守一世寂寞
死守一世寂寞 2020-11-27 23:22

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         


        
相关标签:
1条回答
  • 2020-11-27 23:29

    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.

    0 讨论(0)
提交回复
热议问题