Can multiprocessing Process class be run from IDLE

Posted on

Question :

Can multiprocessing Process class be run from IDLE

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

Answer #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:UsersTerry>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.

Answered By: Terry Jan Reedy

Leave a Reply

Your email address will not be published. Required fields are marked *