从 Python 中的另一个函数中断函数执行

Meh*_*hdi 8 python interrupt

我有一个函数a执行一些任务,另一个函数b是对某些事件的回调。每当发生事件时,b都会调用function并且我想让它能够中断 function 的执行a。这两个函数都在同一个类中声明。

Functiona不应该调用 function b。功能b是完全独立的,它是对来自ROS:机器人操作系统的“用户面部检测”等外部事件的回调。

我需要的基本上是像 Ctrl+C 这样的东西,它可以从 Python 中调用,它只会中止目标函数而不是整个程序。

这可以在 Python 中完成吗?

Ept*_*tin 8

通常建议不要使用异常调用来进行流程控制。threading.Event相反,即使您只计划使用单个线程(即使是最基本的 Python 程序也至少使用一个线程),请查看 python stdlib's 。

这个答案/sf/answers/3244232911/很好地解释了调用一个函数(函数b)如何中断另一个函数(函数a)。

以下是从其他答案中总结的一些重要部分。

设置您的线程库:

from threading import Event
global exit
exit = Event()
Run Code Online (Sandbox Code Playgroud)

这是 的一个很好的替代品time.sleep(60),因为它可以被中断:

exit.wait(60)
Run Code Online (Sandbox Code Playgroud)

此代码将执行,直到您将 exit 更改为“set”:

while not exit.is_set():
    do_a_thing()
Run Code Online (Sandbox Code Playgroud)

这将导致exit.wait(60)停止等待,并将exit.is_set()返回True

exit.set()
Run Code Online (Sandbox Code Playgroud)

这将再次启用执行,exit.is_set()并将返回False

exit.clear()
Run Code Online (Sandbox Code Playgroud)


Bor*_*lik 5

我会做以下事情:

  • 定义自定义异常
  • 在适当的 try/catch 块中调用回调函数
  • 如果回调函数决定中断执行,它将引发异常,调用者将捕获它并根据需要进行处理。

这是一些伪代码:

class InterruptExecution (Exception):
    pass

def function_a():
    while some_condition_is_true():
        do_something()
        if callback_time():
            try:
                function_b()
            except InterruptExecution:
                break
        do_something_else()
    do_final_stuff()


def function_b():
    do_this_and_that()
    if interruption_needed():
        raise (InterruptExecution('Stop the damn thing'))
Run Code Online (Sandbox Code Playgroud)