1 import signal 2 import time 3 4 5 # Define signal handler function 6 def myHandler(signum, frame): 7 exit("TimeoutError") 8 9 10 def test_fun(): 11 # time.sleep(3) 12 int("afsdf") 13 a = 2 + 3 14 15 return a 16 17 18 19 if __name__ == '__main__': 20 try: 21 signal.signal(signal.SIGALRM, myHandler) 22 signal.alarm(2) 23 test = test_fun() 24 print(test) 25 signal.alarm(0) 26 except Exception as ret: 27 print("msg:", ret) 执行结果: 当 time.sleep(3) 时,会抛出TimeoutError的异常 当 test_fun 里面出现 int("afsdf")时, 会抛出 ValueError("invalid literal for int() with base 10: 'afsdf'",)) 当test_fun函数执行的时间小于2 秒时,就会返回函数对应的值