在python中

时间:2017-09-06 12:22:59

标签: python-2.7 python-multiprocessing kill-process

我正在尝试终止一个在超时后运行的进程,它终止了gots。但是被调用的函数一直在运行。我通过多处理调用一个函数,并在函数活动超过10秒时终止该函数。函数1使用子进程在命令行中运行另一个python文件(function2)。 function2依次通过run.py(function3)运行另一个python文件。

因此,当我终止函数1时,它不会终止仍在运行的function2和function3。我需要终止所有三个函数。示例代码如下: Python文件1(功能1)

import multiprocessing
import time
from test_multikill import kit
import subprocess    

count = 0
def bar(cmd):
    print(cmd)
    runcmd = r'\Scripts\python test_files\test_multikill.py'
    subprocess.call(runcmd, shell=True)
    for i in range(30):
        print "Tick"
        time.sleep(1)

def mulpro():
    cmd = 's'
    p = multiprocessing.Process(target=bar, args=cmd)
    p.start()
    # Wait for 10 seconds or until process finishes
    p.join(5) 
    # If thread is still active
    if p.is_alive():
        print "running... let's kill it..."
        # Terminate
        p.terminate()
        global count
        print count
        count += 1
        if count <= 2:
            mulpro()
            print count
        p.join()


if __name__ == '__main__':

    mulpro()

Python文件2(功能2):

import time
import runpy

def kit():
    result = runpy.run_path(r'test_files\test_multikill2.py', run_name='__main__')
    for i in range(30):
        print('I am here', i)
        time.sleep(1)

if __name__ == '__main__':
    kit()

Python文件3(功能3):

import time

def cat():
    for i in range(30):
        print('I am cat', i)
        time.sleep(1)

if __name__ == '__main__':
    cat()

输出:

s
('I am cat', 0)
('I am cat', 1)
('I am cat', 2)
('I am cat', 3)
('I am cat', 4)
running... let's kill it...
0
s
('I am cat', 5)
('I am cat', 0)
('I am cat', 6)
('I am cat', 1)
('I am cat', 7)
('I am cat', 2)
('I am cat', 8)
('I am cat', 3)
('I am cat', 9)
('I am cat', 4)
running... let's kill it...
1
s
('I am cat', 10)
('I am cat', 5)
('I am cat', 0)
('I am cat', 11)
('I am cat', 6)
('I am cat', 1)
('I am cat', 12)
('I am cat', 7)
('I am cat', 2)
('I am cat', 13)
('I am cat', 8)
('I am cat', 3)
('I am cat', 14)
('I am cat', 9)
('I am cat', 4)
running... let's kill it...
2
3
3

1 个答案:

答案 0 :(得分:0)

我们不必使用3种功能。我们可以使用一个多处理函数来调用另一个具有所有必需实现的函数。通过这种方式我们可以轻松地终止一个被多处理调用的函数