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"

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?

解决方案

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.

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.

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")

You can read more about process start strategies in the multiprocessing documentation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值