简体   繁体   English

在Python multiprocessing.Process中,我们是否必须使用`__name__ == __main__`?

[英]In Python multiprocessing.Process , do we have to use `__name__ == __main__`?

I am writing a class that supports easy-to-use API to add different settings to run a given program ( class.add(args) ) and to benchmark all settings with multiprocessing ( class.benchmark(num_processes=5) ). 我正在编写一个支持易于使用的API的类,以添加不同的设置以运行给定程序( class.add(args) )并使用多处理程序对所有设置进行基准测试( class.benchmark(num_processes=5) )。

From the documentation of multiprocessing.Process, it seems all cases using if __name__ == '__main__' . 从multiprocessing.Process的文档中,似乎所有情况都使用if __name__ == '__main__' Is it safe to skip using it ? 跳过使用安全吗?

For example, the class method benchmark(num_processes=5) starts and joins processes, and another python file file.py creates a class and simply call class.benchmark(num_processes=5) . 例如,类方法benchmark(num_processes=5)启动并加入进程,另一个python文件file.py创建一个类,只需调用class.benchmark(num_processes=5) Will it work as usual ? 它会照常工作吗?

if __name__ == '__main__': is used to indicate which code to run when the module is loaded. if __name__ == '__main__':用于指示加载模块时要运行的代码。 Basically, it is loaded either when you run it as a script or when you import it as a library. 基本上,在将其作为脚本运行或作为库导入时都将其加载。 In the first case, one usually writes it so that all of the written code executes so it is not necessary to include it. 在第一种情况下,通常会编写它,以便所有编写的代码都能执行,因此不必包含它。 But when you are writing a library, there might by some code which you don't wont to run when other people import it, such as a short example or tests. 但是,当您编写库时,可能会有一些其他人导入时不会运行的代码,例如简短的示例或测试。 So in the later case, you definitely want to include it. 因此,在后一种情况下,您肯定要包括它。

To answer you question from the comments above, I don't think it makes sense to include it in a class method, as it is top-level construct and so it loads always. 为了从上面的评论中回答您的问题,我认为将它包含在类方法中没有意义,因为它是顶级构造,因此始终会加载。

As described in the multiprocessing guidelines under the heading "Safe importing of main module", some forms of multiprocessing need to import your main module and thus your program may run amok in a fork bomb if the __name__ == '__main__' check is missing. 多处理指南中 “安全导入主模块”标题下所述,某些形式的多处理需要导入主模块,因此,如果__name__ == '__main__'检查,则程序可能会在fork炸弹中运行。 In particular, this is the case on Windows where CPython cannot fork . 特别是在Windows中,CPython无法进行分叉 So it is not safe to skip it. 因此,跳过它是不安全的。 The test belongs at the top (global) level of your module, not inside some class. 测试属于模块的顶级(全局)级别,而不属于某些类。 Its purpose is to stop the module from automatically running tasks (as opposed to defining classes, functions etc) when it is imported, as opposed to run directly. 其目的是阻止模块在导入时自动运行任务(与定义类,函数等相反),而不是直接运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM