等价于Python 3中的thread.interrupt_main() [英] Equivalent of thread.interrupt_main() in Python 3

查看:283
本文介绍了等价于Python 3中的thread.interrupt_main()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中,有一个函数thread.interrupt_main(),当从子线程调用该函数时,该函数会在主线程中引发KeyboardInterrupt异常.

In Python 2 there is a function thread.interrupt_main(), which raises a KeyboardInterrupt exception in the main thread when called from a subthread.

在Python 3中也可以通过_thread.interrupt_main()获得此功能,但这是一个低级的支持模块",主要用于其他标准模块中.

This is also available through _thread.interrupt_main() in Python 3, but it's a low-level "support module", mostly for use within other standard modules.

在Python 3中,如果有的话,大概是通过threading模块执行此操作的现代方式是什么?

What is the modern way of doing this in Python 3, presumably through the threading module, if there is one?

推荐答案

手动引发异常是一种低级的操作,因此,如果您认为必须执行此操作,则只需使用_thread.interrupt_main()即可,因为这与您要求的等效( threading模块本身不提供此功能.

Well raising an exception manually is kinda low-level, so if you think you have to do that just use _thread.interrupt_main() since that's the equivalent you asked for (threading module itself doesn't provide this).

不过,可能有一种更优雅的方法来实现您的最终目标.也许设置和检查标记就足够了,或者使用已经建议的threading.Event,如@RFmyD,或者使用通过queue.Queue传递的消息.这取决于您的特定设置.

It could be that there is a more elegant way to achieve your ultimate goal, though. Maybe setting and checking a flag would be already enough or using a threading.Event like @RFmyD already suggested, or using message passing over a queue.Queue. It depends on your specific setup.

这篇关于等价于Python 3中的thread.interrupt_main()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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