在哪里将freeze_support()放入Python脚本? [英] where to put freeze_support() in a Python script?
问题描述
对于将freeze_support()
用于multiprocessing
感到困惑,我得到了一个没有它的Runtime Error
.我只运行脚本,没有定义函数或模块.我还能使用吗?还是我导入的软件包应该一直在使用它?
I am confused about using freeze_support()
for multiprocessing
and I get an Runtime Error
without 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?
此处是文档.
请注意,特定问题与scikit-learn
调用GridSearchCV
有关,后者试图并行生成进程.我不确定我的脚本是否需要为此冻结,或者是否需要冻结某些代码(来自Anaconda发行版).如果有关此问题的详细信息,请转到更具体的问题.
Note that the specific issue is about scikit-learn
calling GridSearchCV
which 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.
推荐答案
在Windows上,所有multiprocessing
使用代码的全部必须由if __name__ == "__main__":
On Windows all of your multiprocessing
-using code must be guarded by if __name__ == "__main__":
为了安全起见,我会将您当前所有的代码放在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:
if __name__ == "__main__":
main()
请参见此处解释为什么这样做是必要的.您可能根本不需要调用freeze_support
,尽管包含它不会有任何损害.
See the "Safe importing of main module" sub-section here for an explanation of why this is necessary. You probably don't need to call freeze_support
at all, though it won't hurt anything to include it.
请注意,最佳做法是无论如何都要对脚本使用if __name__ == "__main__"
保护,因此,如果以后发现需要将import
脚本转换为另一个脚本,则不会意外执行代码.
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 import
your script into another script at some point in the future.
这篇关于在哪里将freeze_support()放入Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!