gpt4 book ai didi

python - 交互模式下的多处理中断

转载 作者:太空狗 更新时间:2023-10-29 18:02:20 24 4
gpt4 key购买 nike

我有以下代码

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 运行 scirpt 然后运行 ​​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)>

错误来自子进程,主进程运行良好。

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

最佳答案

multiprocessing documentation讨论这个:

Note

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__ 在交互式 session 的上下文中的定义非常不同(因为它与 shell 关联,而不是正在运行的文件)。

关于python - 交互模式下的多处理中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24466804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com