Python での最大実行時間の設定に関していくつか質問があります。実際、pdfminer を使用して PDF ファイルを .txt に変換したいと考えています。問題は、非常に多くの場合、一部のファイルがデコードできず、非常に長い時間がかかることです。time.time()
そこで、各ファイルの変換時間を 20 秒に制限するように設定したいと思います。また、Windows で実行しているため、シグナル機能を使用できません。
(私のコードでは "c" です) で変換コードを実行することに成功しましたが、while ループにpdfminer.convert_pdf_to_txt()
統合できませんでした。time.time()
次のコードでは、while ループとtime.time()
動作しないように思えます。
要約すると、私はしたい:
PDF ファイルを .txt ファイルに変換します
各変換の制限時間は 20 秒です。時間切れの場合は、例外をスローして空のファイルを保存します
すべてのtxtファイルを同じフォルダーに保存します
例外/エラーがある場合でも、ファイルを保存しますが、コンテンツは空にしてください。
現在のコードは次のとおりです。
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("")