是否可以在Python多处理中跳过__main__模块的初始化?

问题描述 投票:0回答:1

在 python 多处理中使用

if __name__ == "__main__"
很常见。但是,如果我知道我的子进程不需要
__main__
模块中的任何内容,我可以删除这部分吗?例如

# test_child.py
from multiprocessing import Process, get_context

def f(x):
    print(f"{x}")

def start():
    ctx = get_context("spawn")
    p = ctx.Process(target=f, args=("hello",))
    p.start()
    p.join()
# test_parent.py
from test_child import start
start()

当我运行

python test_parent.py
时,理想情况下子进程不需要
__main__
模块中的任何内容,因此它可以熟练使用这部分,并且我不需要在
if __name__ == "__main__"
中添加
test_parent.py

目前它会导致错误。

python multiprocessing
1个回答
0
投票

如果将

test_parent.py
导入到任何地方,
start()
将被调用。 Python 是一种脚本语言。

如果您始终直接使用解释器运行脚本而不是

import
,那么很好。只需确保
__name__
test_parent.py
始终为
"__main__"

© www.soinside.com 2019 - 2024. All rights reserved.