gpt4 book ai didi

Python - pdfkit 的超时规则

转载 作者:行者123 更新时间:2023-12-05 07:37:52 29 4
gpt4 key购买 nike

我想知道是否有人知道如何在运行 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 个)

最佳答案

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 中不起作用。

关于Python - pdfkit 的超时规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48345160/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com