如何在python中运行完整脚本停止多处理

时间:2018-01-17 16:54:20

标签: python process multiprocessing python-multiprocessing

我在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"

我的目标是在三个实例中成功发生挂起函数的多处理。我的问题是main函数还在以下输出中运行整个脚本的三个实例:

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

如何阻止这种情况发生?

1 个答案:

答案 0 :(得分:1)

在生成新进程时,Windows会创建一个空白进程。然后在生成的进程中加载​​一个新的Python解释器,并给它相同的代码库来解释。

这就是为什么你看到重复的打印语句被执行的原因。由于它们是顶级表达式,因此每次进程评估该代码时都会执行它们。

在Unix操作系统中,没有观察到这一点,因为它实现了一个完全不同的进程创建机制(data want2; set have; by month; retain open; if first.month then open = close; if last.month then do; range = close - open; relative = range / open; OUTPUT; end; keep month open close range relative; run; 策略),它不需要在子进程中再次加载新的Python解释器。

要解决您的问题,您需要从脚本中删除fork个表达式,然后将其移到print( ... )函数中。

main

您可以在multiprocessing documentation中了解有关流程启动策略的更多信息。