python func_timeout 设置函数超时退出

使用func_timeout设置函数超时退出,使用func_set_timeout装饰器和func_timeout方法

复制代码
from func_timeout import func_set_timeout,exceptions.FunctionTimedOut
import time

@func_set_timeout(3)
def task():
    print('hello world')
    time.sleep(5)
    return '执行成功_未超时'

if __name__ == '__main__':
    try:
        print(task())
    except exceptions.FunctionTimedOut:
        print('执行函数超时')
复制代码

 

应用场景:用opencv链接网络摄像头,但是摄像头的地址不一定是正确的,或者是打开的,当错误的时候会直接报错,但是当地址正确却没有打开,或者网络限制的时候,会等上半天才返回,并且不报错,此时使用func_timeout进行处理

复制代码

from func_timeout import func_timeout, FunctionTimedOut
def catch_video(path):
    start_time = time.time()
    try:
        cap = func_timeout(5, cv.VideoCapture, (path,))        
        if cap.isOpened():
            open_time = time.time() - start_time
            message = 'video open time is :' + "{:.2f}".format(open_time)
        else:
            message = 'can not open the video.'
        cap.release()
    except FunctionTimedOut:
        message = 'open video is timeout'
    except:
        message = 'other error'
    # print(message)
    return message
复制代码

 

posted on   sdlyxyf  阅读(1189)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示