本文介绍了Windows上的python多重处理(如果__name__ =="__main__");的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 7(64位)上运行python 2.7.

Running python 2.7 on windows 7 (64bit).

在阅读库模块multiprocessing的文档时,它指出了__main__模块重要性的几倍,包括条件(尤其是Windows):

When reading the docs for library module multiprocessing, it states several times the importance of the __main__ module, including the conditional (especially in Windows):

if __name__ == "__main__":
    # create Process() here

我的理解是,您不想在模块的全局名称空间中创建Process()实例(因为当子进程导入模块时,他会无意中产生另一个).

My understanding, is that you don't want to create Process() instances in the global namespace of the module (because when the child process imports the module, he will spawn yet another inadvertently).

不过,我不必将流程管理器放在程序包执行层次结构的最顶层(在PARENT中执行).只要在类方法甚至函数闭包中创建,管理和终止我的Process()即可.只是不在顶层模块名称空间中.

I do not have to place Process managers at the very top level of my package execution hierarchy though (execution in the PARENT). As long as my Process()'s are created, managed, and terminated in a class method, or even in a function closure. Just not in the toplevel module namespace.

我是否正确理解此警告/要求?

Am I understanding this warning/requirement correctly?

在前两个响应之后,我添加此引用.这是2.7文档中第16.6节多处理的简介.

After the first two responses, I add this quotation. This is in the introduction for Section 16.6 multiprocessing from the 2.7 docs.

推荐答案

您不必从模块的顶层"调用Process().从类方法中调用Process很好.

You do not have to call Process() from the "top level" of the module.It is perfectly fine to call Process from a class method.

唯一的警告是,导入模块时,不允许调用Process().

The only caveat is that you can not allow Process() to be called if or when the module is imported.

由于Windows没有fork,因此多处理模块将启动一个新的Python进程,并 import 调用该模块.如果Process()在导入时被调用,则这将引发无限连续的新进程(或直到您的计算机用尽资源).这就是将对Process()的调用隐藏在

Since Windows has no fork, the multiprocessing module starts a new Python process and imports the calling module. If Process() gets called upon import, then this sets off an infinite succession of new processes (or until your machine runs out of resources). This is the reason for hiding calls to Process() inside

if __name__ == "__main__"

因为此if-statement中的语句不会在导入时被调用.

since statements inside this if-statement will not get called upon import.

这篇关于Windows上的python多重处理(如果__name__ =="__main__");的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 13:41
查看更多