【问题标题】:Python - Timeout rule on pdfkitPython - pdfkit 上的超时规则
【发布时间】:2018-06-28 22:25:24
【问题描述】:

我想知道是否有人知道在运行 pdfkit 时如何实现超时?

我正在尝试遍历大量 URL 以打印每个 URL 页面的 pdf。有时循环可能会挂断,但是如果需要超过 30 秒,我只想跳过循环中的 URL。我试过了:

for n, i in enumerate(urllist):    
    pdfkit.from_url(i, str(directory) + "\\" + str(idnum[n]) + ".pdf", configuration=config, timeout=30)

上面的代码只是立即结束循环。这段代码在没有“超时”部分的情况下完美运行,但运行 10 个 URL 需要大约 4 分钟(我需要超过 10,000 个)

【问题讨论】:

  • 您使用的是什么版本的 pdfkit?我在 from_url() 中没有超时参数
  • 您找到解决方案了吗?

标签: python python-3.x loops timeout pdfkit


【解决方案1】:

Pdfkitwkhtmltopdf 的包装器,通常在pdfkit 挂起加载页面或其他情况时负责。不幸的是,wkhtmltopdf 还没有超时 (more here),pdfkit 也没有解决问题 (more here)。 所以,不,你不能使用来自pdfkitwkhtmltopdf 的内部超时。

为了在 Windows 中解决这个问题(LINUX 有更好的解决方案),我使用了multiprocessing 包。 请注意,此代码是较大代码的一部分,尚未按原样进行测试。如果它不起作用,请留下反馈:)

import pdfkit, multiprocessing

url = "a_url"

p = multiprocessing.Process(target = pdfkit.from_url, args = (url, pdf_name,)) # Create the process
p.start() # Start the process
p.join(180) # Give it a 180 sec frame to complete before you kill it
if p.is_alive():
    p.terminate() # If after 180 sec its still running, kill it

# Note that if it completes before 180 sec, the script continues (you don't wait 180 sec)
# Note that if you run pdfkit from another function declared in the script you might have problems with multiprocssing. Multiprocssing requires sometimes that functions are imported... for some reason. Just create another file and import it.

在运行 1150 个 4 页 pdf 文件后,我没有观察到内存或 CPU 有任何显着变化


多处理有点像沉重的盔甲,但我尝试过的其他事情没有奏效。 stopit 由于某种原因无法停止该过程。 signal 在 Windows 中不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-15
    • 2020-05-06
    • 2017-11-23
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多