我终于明白了!
首先,定义一个函数来调用另一个具有有限超时的函数: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("")
代码应该很容易理解,如果不是,请随时询问。在
我真的希望这有帮助(,因为我们花了一些时间才把它做好;)!