python设置程序使用时间_python线程.计时器当程序超时时设置时间限制

该博客介绍了如何在Python中使用multiprocessing模块设置函数调用的超时限制。通过创建新进程并在指定时间后检查其状态,可以确保程序在超时时被终止。示例代码展示了如何将此技术应用于文件转换操作,以防止长时间运行的任务阻塞程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我终于明白了!

首先,定义一个函数来调用另一个具有有限超时的函数:import multiprocessing

def call_timeout(timeout, func, args=(), kwargs={}):

if type(timeout) not in [int, float] or timeout <= 0.0:

print("Invalid timeout!")

elif not callable(func):

print("{} is not callable!".format(type(func)))

else:

p = multiprocessing.Process(target=func, args=args, kwargs=kwargs)

p.start()

p.join(timeout)

if p.is_alive():

p.terminate()

return False

else:

return True

函数的作用是什么?在检查超时和函数是否有效

在新进程中启动给定函数,这比线程有一些优势

阻止程序x秒(p.join())并允许在此时执行函数

超时过期后,检查函数是否仍在运行Yes:终止它并返回False

不:很好,没有暂停!返回True

我们可以用time.sleep()进行测试:

^{pr2}$

我们运行一个需要1秒才能完成的函数,超时设置为2秒:No timeout

如果我们运行time.sleep(10)并将超时设置为两秒:finished = call_timeout(2, time.sleep, args=(10, ))

结果:Timeout

请注意,程序在两秒钟后停止,而没有完成调用的函数。在

您的最终代码如下:import converter as c

import os

import timeit

import time

import multiprocessing

yourpath = 'D:/hh/'

def call_timeout(timeout, func, args=(), kwargs={}):

if type(timeout) not in [int, float] or timeout <= 0.0:

print("Invalid timeout!")

elif not callable(func):

print("{} is not callable!".format(type(func)))

else:

p = multiprocessing.Process(target=func, args=args, kwargs=kwargs)

p.start()

p.join(timeout)

if p.is_alive():

p.terminate()

return False

else:

return True

def convert(root, name, g, t):

with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:

newfile.write(c.convert_pdf_to_txt(os.path.join(root, name)))

for root, dirs, files in os.walk(yourpath, topdown=False):

for name in files:

try:

t=os.path.split(os.path.dirname(os.path.join(root, name)))[1]

a=str(os.path.split(os.path.dirname(os.path.join(root, name)))[0])

g=str(a.split("\\")[1])

finished = call_timeout(5, convert, args=(root, name, g, t))

if finished:

print("yes")

else:

print("no")

with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:

newfile.write("")

except KeyboardInterrupt:

raise

except:

for name in files:

t=os.path.split(os.path.dirname(os.path.join(root, name)))[1]

a=str(os.path.split(os.path.dirname(os.path.join(root, name)))[0])

g=str(a.split("\\")[1])

with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:

newfile.write("")

代码应该很容易理解,如果不是,请随时询问。在

我真的希望这有帮助(,因为我们花了一些时间才把它做好;)!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值