本文介绍了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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:58