python - 来自导入文件的 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”(自己的执行名称)时,我得到了上面显示的错误。尝试从另一个文件调用多进程有什么问题?
解决方案
您可以调试以查看名称对应的内容。喜欢将其添加到test2.py
:
def print_name():
print(__name__)
现在你应该看到了,因为它在 module 中test2.py
,所以你在导入这个模块时的名字会有test2
另外,请注意您正在导入test2
,但从不存在的test
. 所以你可能会尝试从你导入的库中调用:
test2.call(0, 7)
推荐阅读
- ios - 单击 UITextField 后应用程序冻结
- django - Django select2,搜索父类别名称时显示子类别
- python - 命令行不识别“python”命令,不让我安装 pip 包
- angular - Ionic v4 App 调试窗口自动从 http 重定向到 https
- javascript - 如何将 Web 插件 (DarkReader) 初始化到我的 html 文档中?
- grails - Grails 4引导程序未运行
- c++ - 在动态内存分配中是否严格要求在 C++ 中使用“free”或“delete”,因为函数只将指针指向的值设置为 0?
- javascript - 构造函数接受 (1) 字符串列表;(2) str 数组;(3) 地图
- ecmascript-6 - Axios Promise 正在解决 undefined
- model-view-controller - 与 sitecore 集成时自定义验证码图像不呈现