【问题标题】:python threading.timer set time limit when program runs out of timepython threading.timer设置程序超时时的时间限制
【发布时间】:2017-04-06 12:33:58
【问题描述】:

我有一些关于在 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. 如果有任何异常/错误,仍然保存文件,但内容为空。

这是当前代码:

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


【解决方案1】:

我终于想通了!

首先,定义一个函数以限制超时调用另一个函数:

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()) 并允许函数在这段时间内执行
  • 超时后,检查函数是否还在运行

    • 是:终止它并返回False
    • 不:好的,没有超时!返回True

我们可以用time.sleep()进行测试:

import time

finished = call_timeout(2, time.sleep, args=(1, ))
if finished:
    print("No timeout")
else:
    print("Timeout")

我们运行一个需要一秒才能完成的函数,超时设置为两秒:

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("") 

代码应该通俗易懂,如果不明白,欢迎追问。

我真的希望这会有所帮助(因为我们需要一些时间才能做到这一点;))!

【讨论】:

【解决方案2】:

检查以下代码,如果有任何问题,请告诉我。另外让我知道您是否仍想使用强制终止功能 (KeyboardInterruption)

path_to_pdf = "C:\\Path\\To\\Main\\PDFs" # No "\\" at the end of path!
path_to_text = "C:\\Path\\To\\Save\\Text\\" # There is "\\" at the end of path!
TIMEOUT = 5  # seconds
TIME_TO_CHECK = 1  # seconds


# Save PDF content into text file or save empty file in case of conversion timeout
def convert(path_to, my_pdf):
    my_txt = text_file_name(my_pdf)
    with open(my_txt, "w") as my_text_file:
         try:
              my_text_file.write(convert_pdf_to_txt(path_to + '\\' + my_pdf))
         except:
              print "Error. %s file wasn't converted" % my_pdf


# Convert file_name.pdf from PDF folder to file_name.text in Text folder
def text_file_name(pdf_file):
    return path_to_text + (pdf_file.split('.')[0]+ ".txt")


if __name__ == "__main__":
    # for each pdf file in PDF folder
    for root, dirs, files in os.walk(path_to_pdf, topdown=False):
        for my_file in files:
            count = 0
            p = Process(target=convert, args=(root, my_file,))
            p.start()
            # some delay to be sure that text file created
            while not os.path.isfile(text_file_name(my_file)):
                time.sleep(0.001)
            while True:
                # if not run out of $TIMEOUT and file still empty: wait for $TIME_TO_CHECK,
                # else: close file and start new iteration
                if count < TIMEOUT and os.stat(text_file_name(my_file)).st_size == 0:
                    count += TIME_TO_CHECK
                    time.sleep(TIME_TO_CHECK)
                else:
                    p.terminate()
                    break

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 2017-03-03
  • 1970-01-01
相关资源
最近更新 更多