【问题标题】:multiprocessing breaks in interactive mode交互模式下的多处理中断
【发布时间】:2014-08-19 10:45:08
【问题描述】:

我有以下代码

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 抱怨:

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

错误来自子进程,主进程运行正常。

这没什么大不了,但我想知道为什么会这样,如果它可以在交互模式下工作就好了

【问题讨论】:

    标签: python multiprocessing


    【解决方案1】:

    multiprocessing documentation 讨论了这个:

    注意

    此包中的功能要求 __main__ 模块是 孩子们可以导入。这在编程指南中有介绍 但是值得在这里指出。这意味着一些例子, 比如 multiprocessing.Pool 的例子在 交互式解释器。

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

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多