python - 如何限制函数调用的执行时间?

标签 python multithreading

我的代码中有一个与套接字相关的函数调用,该函数来自另一个模块,因此不受我的控制,问题是它偶尔会阻塞几个小时,这是完全 Not Acceptable ,我该如何限制函数执行时间我的代码?我想解决方案必须使用另一个线程。

最佳答案

@rik.the.vik 的答案的改进是使用 with statement给超时函数一些语法糖:

import signal
from contextlib import contextmanager

class TimeoutException(Exception): pass

@contextmanager
def time_limit(seconds):
    def signal_handler(signum, frame):
        raise TimeoutException("Timed out!")
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)


try:
    with time_limit(10):
        long_function_call()
except TimeoutException as e:
    print("Timed out!")

关于python - 如何限制函数调用的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/366682/

相关文章:

java - MySQL事务回滚异常: Deadlock found when trying to get lock;

c# - 奇怪的系统.__佳能异常(exception)

ios - Swift 中的线程队列

python - 使用 argparse 解析字符串

javascript - 如何在 folium MarkerClusters 上显示平均值而不是计数?

python - 模块未找到错误: No module named 'fastai.structured'

python - 使用 Python Turtle 进行多线程处理

python - Pygame 迷宫一直卡住

python - 使用 psycopg2 模块将值插入数据库时​​出错

c++ - void* 在 C++ 中为线程数组