Multiprocessor Breaks Interactively

I have the following code

from multiprocessing import Process, Queue from queue import Empty from time import sleep def f(q): n = 100000000 while n != 100000000 // 2: n -= 1 q.put("the awkening!") print("my work here is done") def main(): q = Queue() p = Process(target=f, args=(q,)) p.start() while True: try: print(q.get(block=False)) raise systemexit except Empty: print("i found nothing :(") sleep(2) p.join() 

If I add

 if __name__ == '__main__': main() 

Until the end, use python script_name.py to run, everything works fine. However, if I just ran scirpt using python -i script_name.py , then run main() Python complains:

 Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Python34\lib\multiprocessing\spawn.py", line 98, in spawn_main exitcode = _main(fd) File "C:\Python34\lib\multiprocessing\spawn.py", line 108, in _main self = pickle.load(from_parent) AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)> 

The error arises from the child process, the main process runs normally.

It doesn’t matter, but I wonder why this is happening, it would also be nice if it worked interactively

+8
python multiprocessing
source share
1 answer

Multiprocessing documentation discusses this:

Note

The functionality in this package requires the __main__ module to be imported by children. This is described in the Programming Guide, however it is worth noting here. This means some examples, such as multiprocessors. Use cases will not work in an interactive interpreter.

I understand that __main__ is defined very differently in the context of an interactive session (since it is associated with the shell, not the file that works).

+12
source share

All Articles