如何在运行完整脚本的python中停止多处理 [英] How to stop multiprocessing in python running for the full script

查看:81
本文介绍了如何在运行完整脚本的python中停止多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有以下代码:

I have the following code in python:

import multiprocessing
import time

print "I want this to show once at the beggining"

def leaveout():
    print "I dont Want This to Show"

def hang(input1):
        print "I want this to show 3 times"
        print "Number = %s" % input1

def main():
    p = multiprocessing.Process(target=hang, args=("0"))
    p.start()
    p1 = multiprocessing.Process(target=hang, args=("1"))
    p1.start()
    p2 = multiprocessing.Process(target=hang, args=("2"))
    p2.start()
    p.join()
    p1.join()
    p2.join()

if __name__ == '__main__':
    main()

print "I want this to show once at the end"

我的目标是在成功发生的三个实例中对hang函数进行多处理.我的问题是,main函数还在以下输出中重新运行了整个脚本的三个实例:

My objective is to multiprocesses the hang function in three instances which is happening successfully. My issue is that the main function also runs three instances of the entire script resuting in the following output:

c:\Evopt>python multiprocessingprac.py
I want this to show once at the beggining
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 2
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 1
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 0
I want this to show once at the end

如何阻止这种情况发生?

How can I stop this happening?

推荐答案

在生成新进程时,Windows将创建一个空白进程.然后,在生成的过程中加载了一个新的Python解释器,并为其提供了相同的代码库来进行解释.

When spawning a new process, Windows creates a blank process. A new Python interpreter is then loaded in the spawned process and it's given the same code base to interpret.

这就是为什么您看到重复的打印语句正在执行的原因.由于它们是顶级表达式,因此每次过程评估该代码时都将执行它们.

That's why you see duplicated print statements being executed. As they are top level expressions, they will be executed every time a process will evaluate that code.

在Unix OS中,没有观察到这种情况,因为它实现了完全不同的进程创建机制(fork策略),该机制不需要在子进程中再次加载新的Python解释器.

In Unix OSes this is not observed because it implements a totally different process creation mechanism (the fork strategy) which does not require a new Python interpreter to be loaded again in the child process.

要解决您的问题,您需要从脚本中删除print( ... )表达式并将其移至main函数中.

To fix your issue, you need to remove the print( ... ) expressions from the script and move them into the main function.

def main():
    print("I want this to show once at the beggining")

    p0 = multiprocessing.Process( ... )
    p0.start() 

    ...

    p2.join()

    print("I want this to show once at the end")

您可以在多处理文档.

这篇关于如何在运行完整脚本的python中停止多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆