在 Python 脚本中将 freeze_support() 放在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24374288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:30:42  来源:igfitidea点击:

where to put freeze_support() in a Python script?

pythonruntime-errormultiprocessingscikit-learnanaconda

提问by László

I am confused about using freeze_support()for multiprocessingand I get an Runtime Errorwithout it. I am only running a script, not defining a function or a module. Can I still use it? Or the packages I import should have been using it?

我对使用freeze_support()for感到困惑multiprocessingRuntime Error没有它我得到了。我只是在运行一个脚本,而不是定义一个函数或一个模块。我还能用吗?或者我导入的包应该一直在使用它?

Hereis the documentation.

是文档。

Note that the specific issue is about scikit-learncalling GridSearchCVwhich tries to spawn processes in parallel. I am not sure if my script needs to be frozen for this, or the some code that's called (from the Anaconda distro). If details are relevant to this question, please head over to the more specific question.

请注意,具体问题是关于尝试并行生成进程的scikit-learn调用GridSearchCV。我不确定我的脚本是否需要为此冻结,或者调用的一些代码(来自 Anaconda 发行版)。如果详细信息与此问题相关,请转到更具体的问题

采纳答案by dano

On Windows allof your multiprocessing-using code must be guarded by if __name__ == "__main__":

在 Windows 上,您的所有multiprocessing-using 代码都必须由if __name__ == "__main__":

So to be safe, I would put all of your the code currently at the top-level of your script in a main()function, and then just do this at the top-level:

因此,为了安全起见,我会将当前位于脚本顶层的所有代码放在一个main()函数中,然后在顶层执行此操作:

if __name__ == "__main__":
    main()

See the "Safe importing of main module" sub-section herefor an explanation of why this is necessary. You probably don't need to call freeze_supportat all, though it won't hurt anything to include it.

请参阅此处的“安全导入主模块”小节以了解为什么需要这样做。您可能根本不需要调用freeze_support,尽管包含它不会有任何伤害。

Note that it's a best practice to use the if __name__ == "__main__"guard for scripts anyway, so that code isn't unexpectedly executed if you find you need to importyour script into another script at some point in the future.

请注意,if __name__ == "__main__"无论如何最好对脚本使用保护,这样如果您发现import在将来的某个时候需要将脚本转换为另一个脚本,代码就不会意外执行。