Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 953
PlasticDuck Avatar asked Feb 08 '23 19:02

PlasticDuck


1 Answers

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.

like image 52
Terry Jan Reedy Avatar answered Feb 16 '23 02:02

Terry Jan Reedy