本文介绍了Windows 中的 signal.alarm 替换 [Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数偶尔会挂起.
I have a function that occasionally hangs.
通常我会设置闹钟,但我使用的是 Windows 并且它不可用.
Normally I would set an alarm, but I'm in Windows and it's unavailable.
有没有简单的方法可以解决这个问题,还是我应该创建一个调用 time.sleep()
的线程?
Is there a simple way around this, or should I just create a thread that calls time.sleep()
?
推荐答案
以下是原发帖者如何解决自己的问题:
Here's how the original poster solved his own problem:
结束了一个线程.唯一的技巧是使用 os._exit
而不是 sys.exit
Ended up going with a thread. Only trick was using os._exit
instead of sys.exit
import os
import time
import threading
class Alarm (threading.Thread):
def __init__ (self, timeout):
threading.Thread.__init__ (self)
self.timeout = timeout
self.setDaemon (True)
def run (self):
time.sleep (self.timeout)
os._exit (1)
alarm = Alarm (4)
alarm.start ()
time.sleep (2)
del alarm
print 'yup'
alarm = Alarm (4)
alarm.start ()
time.sleep (8)
del alarm
print 'nope' # we don't make it this far
这篇关于Windows 中的 signal.alarm 替换 [Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!