在 Python multiprocessing.Process 中,我们必须使用 `__name__ == __main__` 吗?
In Python multiprocessing.Process , do we have to use `__name__ == __main__`?
我正在编写一个 class 支持易于使用的 API 以向 运行 给定程序 (class.add(args)
) 添加不同的设置并对所有程序进行基准测试多处理设置(class.benchmark(num_processes=5)
)。
从 multiprocessing.Process 的文档来看,似乎所有情况都使用 if __name__ == '__main__'
。跳过使用它安全吗?
例如,class 方法 benchmark(num_processes=5)
启动并加入进程,另一个 python 文件 file.py
创建一个 class 并简单地调用 class.benchmark(num_processes=5)
。它会照常工作吗?
if __name__ == '__main__':
用于表示加载模块时要运行哪个代码。基本上,它会在您 运行 作为脚本或将其作为库导入时加载。在第一种情况下,通常编写它以便所有编写的代码都执行,因此没有必要包含它。但是当你编写一个库时,可能会有一些你不习惯的代码,当其他人导入它时 运行,例如一个简短的例子或测试。所以在后一种情况下,你肯定要包含它。
为了回答您上面评论中的问题,我认为将它包含在 class 方法中没有意义,因为它是顶级构造,因此它始终会加载。
如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. In particular, this is the case on Windows where CPython cannot fork中所述。所以跳过它是不安全的。该测试属于模块的顶层(全局)级别,而不是某些 class 内部。它的目的是阻止模块在导入时自动 运行ning 任务(而不是定义 classes、函数等),而不是直接 运行。
我正在编写一个 class 支持易于使用的 API 以向 运行 给定程序 (class.add(args)
) 添加不同的设置并对所有程序进行基准测试多处理设置(class.benchmark(num_processes=5)
)。
从 multiprocessing.Process 的文档来看,似乎所有情况都使用 if __name__ == '__main__'
。跳过使用它安全吗?
例如,class 方法 benchmark(num_processes=5)
启动并加入进程,另一个 python 文件 file.py
创建一个 class 并简单地调用 class.benchmark(num_processes=5)
。它会照常工作吗?
if __name__ == '__main__':
用于表示加载模块时要运行哪个代码。基本上,它会在您 运行 作为脚本或将其作为库导入时加载。在第一种情况下,通常编写它以便所有编写的代码都执行,因此没有必要包含它。但是当你编写一个库时,可能会有一些你不习惯的代码,当其他人导入它时 运行,例如一个简短的例子或测试。所以在后一种情况下,你肯定要包含它。
为了回答您上面评论中的问题,我认为将它包含在 class 方法中没有意义,因为它是顶级构造,因此它始终会加载。
如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. In particular, this is the case on Windows where CPython cannot fork中所述。所以跳过它是不安全的。该测试属于模块的顶层(全局)级别,而不是某些 class 内部。它的目的是阻止模块在导入时自动 运行ning 任务(而不是定义 classes、函数等),而不是直接 运行。