首页 > 解决方案 > 如何在 Python 中停止函数中间运行

问题描述

我有很多次不得不在运行过程中停止一个函数,而无法访问它,或者它有数百行代码,如果对每一行进行 if-check 是不可行的,或者它以某种方式被击中。那是由代码本身触发的。

我曾经sys.settrace完成任务,就像在这个 MWE 中一样:

from threading import Event, Thread
import sys
import time

_stop = Event()


def _globaltrace(frame, event, arg):
    """The global trace call handler."""
    if event == 'call':
        return _localtrace
    else:
        return None


def _localtrace(frame, event, arg):
    """The local trace call handler."""
    global _stop
    if _stop.is_set():
        if event == 'line':
            raise Exception()
    return _localtrace


if __name__ == "__main__":

    def long_function():
        # The Function that need to be terminated before it ends.
        # That we _CAN'T_ change anything in.
        print("Long Function Started.")
        while True:
            time.sleep(1)

    def simulate_external_input_callback():
        global _stop
        time.sleep(5)
        print("Kill signal received.")
        _stop.set()

    sys.settrace(_globaltrace)
    th = Thread(target=simulate_external_input_callback)
    th.start()

    try:
        long_function()
    except Exception:
        print("Long Function Killed.")
        # Try to do some cleanup.
    else:
        print("Long function ended normally.")
    print("The program continues, like nothing happened.")
    th.join()  # Just here for clean up.

然后有一个东西来设置事件:_stop.set()在需要时,通过回调或计时器,并有一个 try-except 来捕获它。

但这是一个讨厌的 hack,正如其他人所说,这通常是不必要的。我相信他们,我不能只是想另一种解决方案。

所以我希望有人知道“正确”的解决方案,在没有使用的地方sys.settrace,终端long_function

标签: python

解决方案


推荐阅读