【问题标题】:Timeout Function in Python (For Windows)Python 中的超时函数(适用于 Windows)
【发布时间】:2017-06-13 14:14:32
【问题描述】:

有没有像signal 模块一样创建超时函数但与 Windows 兼容的明确方法?谢谢

【问题讨论】:

  • 你的意思是time.sleep()
  • 是的,使用 time.sleep
  • 你所说的“清晰”是什么意思?如果您搜索“windows python timeout”,网上已经有很多关于这个问题的文章。如果您已经四处搜索过,您发现哪些内容不清楚?是否有一个特定的 Python 函数需要超时,或者您是否正在尝试编写一个可以接受任何其他函数并给它一个超时的函数?
  • 我同意@skrrgwasme。而且,signal 有什么问题?它适用于 Windows,只有少数例外。

标签: python multithreading


【解决方案1】:

是的,它可以在没有信号的窗口中完成,它也可以在其他操作系统中工作。逻辑是创建一个新线程并等待给定时间并使用_thread(在python3中和python2中的线程)引发异常。此异常将在主线程中抛出,如果发生异常,with块将退出。

import threading
import _thread   # import thread in python2
class timeout():
  def __init__(self, time):
    self.time= time
    self.exit=False

  def __enter__(self):
    threading.Thread(target=self.callme).start()

  def callme(self):
    time.sleep(self.time)
    if self.exit==False:
       _thread.interrupt_main()  # use thread instead of _thread in python2
  def __exit__(self, a, b, c):
       self.exit=True

用法示例:-

with timeout(2):
    print("abc")
    #other stuff here

with 块中的程序应在 2 秒内退出,否则将在 2 秒后退出。

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 2011-11-01
    • 1970-01-01
    • 2020-10-05
    • 2013-04-10
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多