给我的印象是,由于在Windows上生成新进程时,多处理python模块无法分叉,因此启动一个新进程将从头开始导入初始模块(以父进程为准)。例如,这意味着任何不受if __name__=='__main__'
子句保护的代码都将在子进程中运行。做一个简单的测试,似乎并非总是如此。
给出以下简单程序包以及具有以下文件结构的脚本:
test.py
test_package
│-- __init__.py
\-- __main__.py
以及以下内容:
# ------------------------------
# __init__.py
# ------------------------------
print("__init__.py",flush=True)
import multiprocessing
def main():
print("Hi from the main function!",flush=True)
p = multiprocessing.Process(
target=print,args=("Hi from the process!",),kwargs={'flush': True}
)
p.start()
p.join()
# ------------------------------
# __main__.py
# ------------------------------
print("__main__.py",flush=True)
from . import main
if __name__ == __name__ == "__main__":
print("Hi from the main file!",flush=True)
main()
# ------------------------------
# test.py
# ------------------------------
print("test.py",flush=True)
import test_package
if __name__ == "__main__":
print("Hi from the test script!",flush=True)
test_package.main()
按预期运行test.py,输出以下内容:
IN > python test.py
OUT> test.py
__init__.py
Hi from the test script!
Hi from the main function!
test.py
__init__.py
Hi from the process!
但是,当我使用python -m
作为脚本运行模块时,会得到:
IN > python -m test_package
OUT> __init__.py
__main__.py
Hi from the main file!
Hi from the main function!
Hi from the process!
我希望在子进程输出之前先打印__init__.py
。这两个用例有何不同?我想念什么?