I have some questions related to setting the maximum running time in Python. In fact, I would like to use pdfminer to convert the PDF files to .txt. The problem is that very often, some files are not possible to decode and take an extremely long time. So I want to set time.time()
to limit the conversion time for each file to 20 seconds. In addition, I run under Windows so I cannot use signal function.
I succeeded in running the conversion code with pdfminer.convert_pdf_to_txt()
(in my code it is "c"), but I could not integrate the time.time()
in the while loop. It seems to me that in the following code, the while loop and time.time()
do not work.
In summary, I want to:
Convert the PDf file to a .txt file
The time limit for each conversion is 20 seconds. If it runs out of time, throw an exception and save an empty file
Save all the txt files under the same folder
If there are any exceptions/errors, still save the file, but with empty content.
Here is the current code:
import converter as c
import os
import timeit
import time
yourpath = 'D:/hh/'
for root, dirs, files in os.walk(yourpath, topdown=False):
for name in files:
t_end = time.time() + 20
try:
while time.time() < t_end:
c.convert_pdf_to_txt(os.path.join(root, name))
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"
if time.time() > t_end:
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("")