【发布时间】:2017-04-06 12:33:58
【问题描述】:
我有一些关于在 Python 中设置函数的最大运行时间的问题。其实我想用pdfminer把.pdf文件转换成.txt。
问题是很多时候,有些文件无法解码并且需要很长时间。所以我想设置threading.Timer() 将每个文件的转换时间限制为5秒。另外,我是在windows下运行的,所以不能用signal这个模块。
我成功地使用pdfminer.convert_pdf_to_txt() 运行转换代码(在我的代码中它是“c”),但我不确定以下代码中的threading.Timer() 是否有效。 (我认为它没有适当地限制每次处理的时间)
总之,我想:
将pdf转换为txt
每次转换的时间限制为5秒,如果超时,抛出异常并保存一个空文件
将所有txt文件保存在同一个文件夹下
如果有任何异常/错误,仍然保存文件,但内容为空。
这是当前代码:
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("")
【问题讨论】:
-
会再考虑一下 :)
-
@linusg 太好了!谢谢 :))
-
这应该可以了,终于:)
-
@SXC88,我没有使用
pdfminer的经验,但我检查过它不包含convert_pdf_to_txt()方法,converter.convert_pdf_to_txt()... 你的意思是pdfminer.PDFConverter? -
您好,如果您想看一下,我刚刚在下面发布了 converter.convert_pdf_to_txt() 函数,但我实际上可以毫无问题地转换所有这些文件,但是一旦我尝试为其添加时间限制,代码无法正常工作...@Andersson
标签: python multithreading timer timeout