多处理Python 3.6.5中的错误,在3.6.1中没有出现

时间:2018-05-16 01:20:36

标签: python python-3.x multiprocessing

这适用于3.6.1

import multiprocessing

def test1(txt1):
    print(txt1)

txt1 = 'txt here'
test = multiprocessing.Process(target=test1, kwargs={"txt1": txt1})
test.start()

3.6.5中的相同代码失败:

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.

这适用于3.6.5

import multiprocessing

def test1(txt1):
    print(txt1)

if __name__ == '__main__':

    multiprocessing.freeze_support()
    txt1 = 'txt here'
    test= multiprocessing.Process(target=test1, kwargs={"txt1": txt1})
    test.start()

我有一个更复杂的目录结构,需要在process之外启动__main__这样的内容......

one.py

import two
two.call3('txt here')

two.py

import three
import multiprocessing

def call3(txt1):
    test= multiprocessing.Process(target=three.test1, kwargs={"txt1": txt1})
    test.start()

three.py

def test1(txt1):
    print(txt1)

如何让它工作而不是返回上面的错误信息?

2 个答案:

答案 0 :(得分:0)

您可能应该重新考虑在import上执行代码的决定。作为一种解决方法,这样的事情应该有效(假设one.py是你的主文件):

<强> one.py

import multiprocessing
multiprocessing.freeze_support()

import two
two.call3('txt here')

答案 1 :(得分:0)

这是一个解决方案,我仍在测试它是否适用于更复杂的代码设计,但看起来它解决了这个问题。

<强> one.py

import two

if __name__ == '__main__':
    two.call3('txt here')

对于冻结,将multiprocessing.freeze_support()添加到 one.py 可能是个好主意,因为错误消息显示,但是否则代码似乎在没有它的情况下运行。