学无先后,达者为师

网站首页 Python教程 正文

Python 函数超时操作——限制函数运行时间超时则退出执行

作者:懒是一种态度 更新时间: 2022-02-06 Python教程

 简单讲讲,test_fun 是我们要限定运行时间的函数,里面模拟了运行 5 秒。FTimer 是一个线程类,在 run 函数中调用 test_fun。

原理:main函数运行的时候,通过新开一个线程运行要限定的函数,并通过 sleep 设定一个超时等待时间,等待时间一到,就手动将线程终止。

import time
from multiprocessing.context import Process

def test_fun(sfz):
  print("开始运行,我读到了参数:",sfz)
  time.sleep(5) # 模拟超时运行的情况
  print('这里超时运行')

class FTimer(Process):
    def __init__(self, sfz):
      super().__init__()
      self.sfz = sfz
      pass

    def run(self):
        test_fun(self.sfz)


def main():
  sfz="测试参数"

  p = FTimer(sfz)
  p.daemon = True
  p.start()

  time.sleep(2) # 设定函数超时时间,超过2秒将停止函数运行
  p.terminate()

  time.sleep(20) # 等待一下看看线程是否真的退出了

if __name__ == '__main__':
    main()

原文链接:https://blog.csdn.net/shengshuai/article/details/120922913

栏目分类
最近更新