0

Python multiprocessing module

I'm researching about the multiprocessing module and found this 5 years old code. After uncommented the last 2 lines and add a few extra printing, I come up with this code: import multiprocessing as mp def sqr(x): print(f'x: {x}') print(x**2) return x**2 print(mp.cpu_count(), 'cpu count') with mp.Pool(2) as p: p.map(sqr, list(range(10))) It runs fine in the playground. However, when I copied it to IDLE and run it from there, it only prints the number of CPU counts and keep running but no output. Then I switch to powershell and run it, it keeps outputting error message. While the screen rolling fast, I notice RuntimeError if __name__ == '__main__': freeze_support() So I added it at the end, still not working in IDEL & powershell. Then I use vscode, without the if statement, it runs fine without issue. Can anyone explain? https://sololearn.com/compiler-playground/cmaEN3hjgaXf/?ref=app

11th Dec 2024, 10:03 AM
Wong Hei Ming
Wong Hei Ming - avatar
3 ответов
0
with idle, you have to first open a cmd terminal or powershell and type python -m idlelib this will make the terminal receive the idle run output and your complete output will be displayed here. also, using if __name__ == '__main__': with mp.Pool(2) as p: p.map(swr, list(range(10))) is a good idea if I used pwsh or cmd to run a saved python file with the multiprocessing code, I get the correct result, so I can't confirm that part.
12th Dec 2024, 3:39 AM
Bob_Li
Bob_Li - avatar
0
I turned to Python module of the week https://pymotw.com/3/multiprocessing/basics.html Created the first example in IDLE, saved in a file and run it the normal way, nothing happen. Turn to powershell, python testing.py, and it runs. Then I found this article. https://stackoverflow.com/questions/35293178/can-multiprocessing-process-class-be-run-from-idle As suggested, same as yours, run below command in terminal. python -m idlelib It opens another IDLE with a different icon. Open my saved code from the new window, hit F5, nothing shows on IDLE, but it got printed in terminal... Still scratching head...
12th Dec 2024, 4:05 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
from the SO discussion, it's a Windows Idle quirk.
12th Dec 2024, 4:08 AM
Bob_Li
Bob_Li - avatar