我有一些关于在Python中设置函数最大运行时间的问题,实际上我想使用pdfminer将.pdf文件转换为.txt文件。
问题在于,很多时候,有些文件无法解码并且需要非常长的时间。因此,我想使用threading.Timer()来限制每个文件的转换时间为5秒钟。另外,我在Windows下运行,因此不能使用signal模块。
我已经成功地使用pdfminer.convert_pdf_to_txt()(在我的代码中是“c”)运行了转换代码,但我不确定在下面的代码中,threading.Timer()是否有效。(我认为它没有正确地约束每个处理的时间)
简而言之,我想要:
1. 将PDF转换为TXT 2. 每次转换的时限为5秒钟,如果超过时间限制,则抛出异常并保存一个空文件。 3. 将所有txt文件保存在同一个文件夹中。 4. 如果有任何异常/错误,仍然保存文件,但内容为空。
以下是当前代码:
问题在于,很多时候,有些文件无法解码并且需要非常长的时间。因此,我想使用threading.Timer()来限制每个文件的转换时间为5秒钟。另外,我在Windows下运行,因此不能使用signal模块。
我已经成功地使用pdfminer.convert_pdf_to_txt()(在我的代码中是“c”)运行了转换代码,但我不确定在下面的代码中,threading.Timer()是否有效。(我认为它没有正确地约束每个处理的时间)
简而言之,我想要:
1. 将PDF转换为TXT 2. 每次转换的时限为5秒钟,如果超过时间限制,则抛出异常并保存一个空文件。 3. 将所有txt文件保存在同一个文件夹中。 4. 如果有任何异常/错误,仍然保存文件,但内容为空。
以下是当前代码:
import converter as c
import os
import timeit
import time
import threading
import thread
yourpath = 'D:/hh/'
def iftimesout():
print("no")
with open("D:/f/"+g+"&"+t+"&"+name+".txt", mode="w") as newfile:
newfile.write("")
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
try:
timer = threading.Timer(5.0,iftimesout)
timer.start()
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(c.convert_pdf_to_txt(os.path.join(root, name)))
print("yes")
timer.cancel()
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("")
pdfminer
,但我已经检查过它,发现它不包含convert_pdf_to_txt()
方法或者converter.convert_pdf_to_txt()
... 你是指pdfminer.PDFConverter
吗? - Andersson