从Python中的另一个函数执行中断函数执行 [英] Interrupt function execution from another function in Python

查看:174
本文介绍了从Python中的另一个函数执行中断函数执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function a doing some tasks and another function b being a callback to some events. Whenever an event happens, function b is called and I would like to make it able to interrupt the execution of function a. Both functions are declared inside the same class.

函数 a 不应调用函数 b .函数 b 是完全独立的,它是对来自ROS:机器人操作系统的外部事件(如检测到用户面部")的回调.

Function a is not supposed to call function b. Function b is totally independent, it is a callback to an external event like "user face detected" coming from ROS: robot operating system.

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

what I need is basically something like Ctrl+C that can be called from within Python and which only aborts a targeted function and not the whole program.

这可以用Python完成吗?

Can this be done in Python?

推荐答案

通常建议不要对流控制使用异常调用.相反,请查看python stdlib的 threading.Event ,即使您仅计划使用一个线程(即使最基本的Python程序也至少使用一个线程).

It's generally recommended not to use exception calling for flow-control. Instead, look to python stdlib's threading.Event, even if you only plan on using a single thread (even the most basic Python program uses at least one thread).

此答案 https://stackoverflow.com/a/46346184/914778 很好地解释了如何调用一个功能(功能b)可能会中断另一个功能(功能a).

This answer https://stackoverflow.com/a/46346184/914778 has a good explanation of how calling one function (function b) could interrupt another (function a).

以下是其他答案中的一些重要部分.

Here's a few important parts, summarized from that other answer.

设置线程库:

from threading import Event
global exit
exit = Event()

这可以很好地替代 time.sleep(60),因为它可能会中断:

This is a good replacement for time.sleep(60), as it can be interrupt:

exit.wait(60)

该代码将执行,直到您将退出状态更改为"set"为止:

This code will execute, until you change exit to "set":

while not exit.is_set():
    do_a_thing()

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

This will cause exit.wait(60) to stop waiting, and exit.is_set() will return True:

exit.set()

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

This will enable execution again, and exit.is_set() will return False:

exit.clear()

这篇关于从Python中的另一个函数执行中断函数执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆