Skip to main content
 首页 » 编程设计

python之如何突然终止正在进行的处理

2024年11月01日8xxx_UU

我正在尝试使用子进程调用来调用 python 函数。我见过很多子进程的例子,但没有看到任何调用另一个 python 函数的例子。我不确定是否可以完成。

我的函数 fakeFxn 执行一些可能需要几秒钟或长达几个小时的处理。我想跳过那些需要超过特定时间的,比如 1 小时。该函数还返回了一些我需要收集的值。

def fakeFxn(val): 
    if (val== "terminate"): 
        for i in range(10): 
            z = "t" 
        return(z) 
    else: 
        for i in range(100000000): #Instead of infinite loop, here I am doing some big computation 
            y = "nt" 
        return(y) 
 
 
import subprocess 
elapsedTime = 0 
p = subprocess.Popen(retval = fakeFxn("terminate")) 
rc = p.poll()  #returncode 
while (rc == None): 
    sleep(5) 
    elapsedTime = elapsedTime + 5 
    if(elapsedTime <10): 
        rc = p.poll() 
        continue 
    else: 
        rc = "timeout" 
        p.kill() 
        break 

这样做好吗?还是有其他方法可以做到这一点?我在这里问了一个相关问题:Abruptly stop executing a command and continue to the next one

我的实际功能是这篇帖子的``rpart`功能。

请您参考如下方法:

不确定是否通过 subprocess,但您应该能够在 multiprocessing 和包装函数的帮助下完成此操作:

import time 
from Queue import Empty 
from multiprocessing import Process, Queue 
 
def fakeFxn(val): 
    if val == 'terminate': 
        time.sleep(0.1) 
        return 't' 
    else: 
        time.sleep(1000) 
        return 'nt' 
 
def ffWrapper(val, queue): 
    retval = fakeFxn(val) 
    queue.put(retval) 
 
if __name__ == '__main__': 
    q = Queue() 
    p = Process(target=ffWrapper, args=('terminate', q)) 
    p.start() 
    rc = '' 
    try: 
        rc = q.get(timeout=10) 
    except Empty: 
        print 'timeout' 
    p.terminate() 
    print rc