我在Win7x64上有三个脚本,Python 2.7.9(kivy)。
multiprocessing_1
def Multiprocessing_3():
print "Hohoo!"
import multiprocessing_3
multiprocessing_3.LetseGo()
print "It'se me,",__name__," !!"
if __name__ == "__main__":
import multiprocessing_2
multiprocessing_2.main()
multiprocessing_2
import multiprocessing
def main():
print "YA!"
import multiprocessing_1
Multiprocessing3 = multiprocessing.Process(target=multiprocessing_1.Multiprocessing_3,args=(''))
Multiprocessing3.start()
multiprocessing_3
def LetseGo():
print "YAHoooooooo!"
我的问题是关于在执行python multiprocessing_1.py
之后我被抛出的输出:
It'se me, __main__!!
YA!
It'se me, multiprocessing_1!!
It'se me, __parents_main__!!
It'se me, multiprocessing_1!!
Hohoo!
YAHoooooooo!
或在此处查看输出:http://i.imgur.com/ROtLAaZ.png
_1
以__main__
开头,然后导入并调用_2
,然后生成进程_1.Multiprocessing_3
,导入并执行_3.LetseGo()
。
然而,正在发生的事情是_1
实际上运行四次次,而不是我实际预期的那两次。
你能告诉我为什么吗?
答案 0 :(得分:4)
这种情况正在发生,因为您在Windows上运行代码,并且Windows需要在子进程中re-import your __main__
module(恰好是multiprocessing_1.py
)才能执行您传递的功能到multiprocessing.Process
。此外,要在子进程中调用的函数Multiprocessing_3
需要进行pickle才能将其从父进程发送到子进程,并且取消对子进程中的函数的修改需要导入该函数所属的模块再来一次,是multiprocessing_1
。所以每个输出的解释是:
It'se me, __main__!! # multiprocessing_1 is imported when you execute it directly.
YA!
It'se me, multiprocessing_1!! # multiprocessing_2.py calls 'import multiprocessing_1'
It'se me, __parents_main__!! # after you call multiprocessing3.start(), the child process needs to re-import the `__main__` module of your script, which is multiprocessing_1.py
It'se me, multiprocessing_1!! # This import happens so that the Multiprocessing_3 function can be unpickled in the child.
Hohoo!
YAHoooooooo!