【发布时间】:2017-08-05 17:52:18
【问题描述】:
我正在创建一个类,在初始化它时,我正在调用(多进程)它的函数。当我从同一个 .py 文件创建此类时,一切正常。但是,当我从另一个 .py 文件初始化这个类时 - 它失败并抛出一个错误......为什么?
MyDummyClass.py:
import multiprocessing
class MyDummyClass:
def __init__(self):
print("I am in '__init__()'")
if __name__ == 'MyDummyClass':
p = multiprocessing.Process(target=self.foo())
p.start()
def foo(self):
print("Hello from foo()")
example.py:
from MyDummyClass import MyDummyClass
dummy = MyDummyClass()
当我运行 example.py 时,我收到此错误:
I am in '__init__()'
Hello from foo()
I am in '__init__()'
Hello from foo()
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Python\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Python\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Python\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="__mp_main__")
File "C:\Python\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Python\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Python\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "E:\Dropbox\Docs\Business\_NZTrackAlerts\Website\Current dev\NZtracker\cgi-bin\example1.py", line 2, in <module>
dummy = MyDummyClass()
File "...path to my file...\MyDummyClass.py", line 13, in __init__
p.start()
File "C:\Python\lib\multiprocessing\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Python\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Python\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Python\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
File "C:\Python\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
_check_not_importing_main()
File "C:\Python\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.''')
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
我不明白(也不是从其他帖子中)如何解决它。
非常感谢您的帮助!!
【问题讨论】:
标签: python django python-3.x python-multiprocessing python-multithreading