我有以下代码:
如果我添加
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)>
出现错误是由于子进程,主进程正常运行。
这不是什么大问题,但我想知道为什么会发生这种情况,同时如果可以在交互模式下运行就更好了。