[英]Why does my python script continue while if __name__==__main__ runs?
Below is a simplified version of a problem I'm facing.以下是我面临的问题的简化版本。 When I run my code, example below, why does the script run code below the if _name__==__main_ section while the function which sits underneath the if statement is still running?当我运行我的代码时,下面的示例,为什么脚本在 if _name__==__main_ 部分下面运行代码,而位于 if 语句下面的函数仍在运行? I thought the p_1.join() command should block the script from continuing until the separate process has finished.我认为 p_1.join() 命令应该阻止脚本继续,直到单独的进程完成。 In the output below I'm expecting the word "Finished" to only be printed when all of the script has concluded - but instead it is being printed second and then last.在下面的输出中,我希望只有在所有脚本都结束时才打印“完成”这个词 - 但它是第二次打印,然后是最后一次打印。
In the past I have used poolexecutor for similar problems;过去我曾使用 poolexecutor 解决类似的问题; but in this project I need to start each process individually so that I can assigned separate independent functions to each process.但在这个项目中,我需要单独启动每个流程,以便我可以为每个流程分配单独的独立功能。
import time
from multiprocessing import Process, Queue
def a(x,q):
time.sleep(3)
q.put(x*x)
q=Queue()
def main():
print("Main Function Starts")
p_1 = Process(target=a, args=(5,q))
p_1.start()
p_1.join()
b= q.get()
print(b)
print("Main Function Ends")
if __name__ == '__main__':
main()
print("Finished")
**Output:**
Main Function Starts
Finished
25
Main Function Ends
Finished
You were supposed to put that code in the if __name__ == '__main__'
guard.您应该将该代码放在if __name__ == '__main__'
守卫中。 Preventing this kind of thing is the whole point of if __name__ == '__main__'
.防止这种事情是if __name__ == '__main__'
。
You're on Windows.你在 Windows 上。 When you start p_1
, multiprocessing
launches a separate Python process, and one of the first things that process does is import your file as a module.当您启动p_1
, multiprocessing
启动一个单独的 Python 进程,该进程所做的第一件事就是将您的文件作为模块导入。 When it does that, the module's __name__
isn't '__main__'
, so anything inside the if __name__ == '__main__'
guard doesn't run, but print("Finished")
is outside the guard.当它这样做时,模块的__name__
不是'__main__'
,所以if __name__ == '__main__'
守卫内的任何东西都不会运行,但print("Finished")
在守卫之外。
Your program isn't somehow continuing past main()
while main()
is still running.当main()
仍在运行时,您的程序不会以某种方式继续通过main()
。 The worker process is performing the unwanted print.工作进程正在执行不需要的打印。
How do you run your script?你如何运行你的脚本? When I ran your script on command line, 'Finished' was printed once like below.当我在命令行上运行你的脚本时,'Finished' 被打印一次,如下所示。
$ python test.py
Main Function Starts
25
Main Function Ends
Finished
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.