加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python – 取消计时器线程

发布时间:2020-12-20 12:42:11 所属栏目:Python 来源:网络整理
导读:我正在尝试创建一个在我的主脚本后台运行在计时器上的方法: def hello_world(self): print 'Hello!' threading.Timer(2,hello_world).start()if __name__ == "__main__": try: hello_world() except KeyboardInterrupt: print 'nGoodbye!' 当我尝试键盘中
我正在尝试创建一个在我的主脚本后台运行在计时器上的方法:

def hello_world(self):
        print 'Hello!'
        threading.Timer(2,hello_world).start()

if __name__ == "__main__":
    try:
        hello_world()
    except KeyboardInterrupt:
        print 'nGoodbye!'

当我尝试键盘中断我的脚本时收到此消息:

Exception KeyboardInterrupt in <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py'> ignored

如何关闭线程以便我可以干净地退出应用程序?

解决方法

为了详细说明Aphex的答案,主线程不可能捕获KeyboardInterrupt信号,除非你有非常快的手指.主线程几乎立即退出!试试这个:

import threading

def hello_world():
        print 'Hello!'
        threading.Timer(2,hello_world).start()

if __name__ == "__main__":
    try:
        hello_world()
    except KeyboardInterrupt:
        print 'nGoodbye!'
    print "main thread exited"

更一般地说,我不建议像这样使用自调用计时器,因为它会创建大量线程.只需创建一个线程并在其中调用time.sleep.

但是,只要你保持主线程运行,你似乎能够在里面捕获KeyboardInterrupt.然后诀窍是使线程成为主线程退出时退出的守护线程.

import threading
import time

def hello_world():
    while(True):
        print 'Hello!'
        time.sleep(2)

if __name__ == "__main__":
    hw_thread = threading.Thread(target = hello_world)
    hw_thread.daemon = True
    hw_thread.start()
    try:
        time.sleep(1000)
    except KeyboardInterrupt:
        print 'nGoodbye!'

这会在1000秒后自动退出 – 如果您愿意,可以使该数字更大.您也可以使用忙循环重复睡眠呼叫,但我真的没有看到这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读