交互模式下的多处理中断 [英] multiprocessing breaks in interactive mode

查看:83
本文介绍了交互模式下的多处理中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

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 __name__ == '__main__':
     main()

最后,使用python script_name.py运行它,一切正常.但是,如果我只是使用python -i script_name.py运行脚本,则运行main() Python会抱怨:

To the end then use python script_name.py to run it, everything works fine. However, if I just run the 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 comes from the child process, the main process runs fine.

这没什么大不了的,但是我想知道为什么会发生这种情况,如果它在交互模式下工作也很好

This is not a big deal, but I wonder why this happens, also it would be nice if it works in interactive mode

推荐答案

多处理文档对此进行了讨论:

注意

此软件包中的功能需要__main__模块为 由儿童进口.编程指南中对此进行了介绍 但是这里值得指出.这意味着一些例子, 例如multiprocessing.Pool范例无法在 交互式口译员.

Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter.

我的理解是,__main__在交互式会话的上下文中的定义非常不同(因为它与shell关联,而不是与正在运行的文件关联).

My understanding is that __main__ is defined very differently in the context of an interactive session (as it is associated with the shell, not the file that is running).

这篇关于交互模式下的多处理中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆