多处理代码重复运行

Har*_*ton 2 python runtime-error multiprocessing

所以我希望使用python多处理模块创建一个进程,我希望它是一个更大的脚本的一部分.(我也想要很多其他的东西,但现在我会满足于此)

我从多处理文档中复制了最基本的代码并稍微修改了一下

但是,每次调用p.join()时,语句之外的所有内容if __name__ == '__main__':都会重复.

这是我的代码:

from multiprocessing import Process

data = 'The Data'
print(data)

# worker function definition
def f(p_num):
    print('Doing Process: {}'.format(p_num))

print('start of name == main ')

if __name__ == '__main__':
    print('Creating process')
    p = Process(target=f, args=(data,))
    print('Process made')
    p.start()
    print('process started')
    p.join()
    print('process joined')

print('script finished')
Run Code Online (Sandbox Code Playgroud)

这是我的预期:

The Data
start of name == main 
Creating process
Process made
process started
Doing Process: The Data
process joined
script finished

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

这是现实:

The Data
start of name == main 
Creating process
Process made
process started
The Data                         <- wrongly repeated line
start of name == main            <- wrongly repeated line
script finished                  <- wrongly executed early line
Doing Process: The Data
process joined
script finished

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是由if声明p.join()或其他内容以及为什么会发生这种情况引起的.有人可以解释是什么造成的,为什么

为清楚起见,因为有些人无法复制我的问题,但我有; 我使用的是Windows Server 2012 R2 Datacenter,我使用的是python 3.5.3.

小智 5

Multiprocessing在Python中的工作方式是每个子进程都导入父脚本.在Python中,导入脚本时,将执行函数中未定义的所有内容.根据我的理解,__name__在导入脚本时进行了更改(请在此处查看此答案以便更好地理解),这与在命令行上直接运行脚本不同,这将导致__name__ == '__main__'.此导入导致__name__不等于'__main__',这就是为什么if __name__ == '__main__':不对您的子进程执行代码.

您不希望在子if __name__ == '__main__':进程调用期间执行的任何操作都应该移动到您的代码部分,因为这只会运行父进程,即您最初运行的脚本.

希望这个对你有帮助.如果您环顾四周,Google周围还有更多资源可以更好地解释这一点.我链接了多处理模块的官方Python资源,我建议你仔细研究它.