首页 > 解决方案 > 来自导入文件的 Python 多处理

问题描述

请继续进行 las 编辑

我面临一些问题,以使此代码正确运行。这应该很容易,但有些东西我不能用“if name = ' main '”正确管理

我有 2 个文件,test1 和 test2,它的工作原理很简单:

测试1

import test2

test2.call(0,7)

测试2

import multiprocessing as mp

in1 = 0
in2 = 0

def cube(x):
    return x ** 3

def call(data1, data2):
    global in1
    global in2
    in1 = data1
    in2 = data2


if __name__ == '__main__':
    pool = mp.Pool(processes=7)
    results = [pool.apply_async(cube, args=(x,)) for x in range(in1, in2)]
    output = [p.get() for p in results]
    print(output)

由于“__ main __”条件,我无法运行多进程,但如果我将条件更改为“test1”,则不会发生任何事情,并且以“test2”作为条件,我会收到一个带有错误的无限循环:

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.

我应该如何进行?

更多

你好,

我刚刚在文档中读到:“在 Windows 以外的任何操作系统上调用时,调用 freeze_support() 无效。此外,如果模块正在由 Windows 上的 Python 解释器正常运行(程序没有被冻结),然后 freeze_support() 没有效果。”

我的脚本正在发生吗?我总是使用 Python 解释器在 Pycharm 中获得无限循环。我怎么能测试它?

新尝试

如果我直接执行这个脚本,它可以工作并且我得到我的计算。

def cube(x):
    calc = x ** 3
    print(calc)
    return calc

if __name__ == '__main__':

print('hola')
x = 2
y = 4
p1 = mp.Process(target=cube, args=(x,))
p2 = mp.Process(target=cube, args=(y,))

p1.start()
p2.start()

p1.join()
p2.join()

但是,当我从另一个文件执行它并将条件 __ main __ 更改为“test2”(自己的执行名称)时,我得到了上面显示的错误。尝试从另一个文件调用多进程有什么问题?

标签: pythonmultiprocessing

解决方案


您可以调试以查看名称对应的内容。喜欢将其添加到test2.py

def print_name():
    print(__name__)

现在你应该看到了,因为它在 module 中test2.py,所以你在导入这个模块时的名字会有test2

另外,请注意您正在导入test2,但从不存在的test. 所以你可能会尝试从你导入的库中调用:

test2.call(0, 7)

推荐阅读