我尝试使用导入的模块实例化对象。为了使这些导入过程安全(因为我在Windows上),我使用:
块内的-
语句。
我的文件看起来有点像这样:
main.py
InstantPattern
foo.py
import
bar.py
if __name__ == '__main__':
输出
# main.py
from multiprocessing import Process
# target func for new process
def init_child(foo_obj, bar_obj):
pass
if __name__ == "__main__":
# protect imports from child process
from foo import getFoo
from bar import getBar
# get new objects
foo_obj = getFoo()
bar_obj = getBar()
# start new process
child_p = Process(target=init_child, args=(foo_obj, bar_obj))
child_p.start()
# Wait for process to join
child_p.join()
我得到的输出表明# foo.py
import os
print 'Foo Loaded by PID: ' + str(os.getpid())
class Foo:
def __init__(self):
pass
def getFoo():
# returning new instance of class
return Foo()
模块已加载两次。我理解解释器再次执行主模块(因为Windows不支持# bar.py
import os
print 'Bar Loaded by PID: ' + str(os.getpid())
class Bar:
def __init__(self):
pass
def getBar():
# not returning a new instance
return 'bar'
系统调用),但奇怪的是它是在Foo Loaded by PID: 58760
Bar Loaded by PID: 58760
Foo Loaded by PID: 29376
块中导入的。
共享对象时可能会出现问题;像从专用模块导入的队列。可能导致这种情况的任何想法?
谢谢!