gpt4 book ai didi

如果互联网中断一段时间,python wget 库不会返回。如果互联网出现故障,如何返回错误?

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:37 24 4
gpt4 key购买 nike

我有下面的代码来在循环内下载文件,

import wget
try:
wget.download(url)
except:
pass

但是如果互联网出现故障,它就不会恢复!所以我的整个循环被卡住了。

如果互联网出现故障,我想重复相同的下载。所以我想知道是否发生任何错误。

我该如何缓解这种情况?

最佳答案

一个简单的解决方案是将下载代码移动到一个线程,并使其成为一个可以中断的单独进程。

您可以使用python Thread和Timer模块来实现它。

from threading import Thread, Timer
from functools import partial
import time
import urllib

def check_connectivity(t):
try:
urllib.request.urlopen("http://google.com", timeout=2)
except Exception as e:
t._Thread__stop()

class Download(Thread):


def run(self):
print("Trying to download file....")
con = partial(check_connectivity, self)
while True:
t = Timer(5, con) # Checks the connectivity every 5 second or less.
t.start()
# your download code....




def main():
down = Download()
down.start()
down.join()

您可以在线程的 run 方法中编写主下载循环的代码。并启动一个计时器来监听网络连接。

关于如果互联网中断一段时间,python wget 库不会返回。如果互联网出现故障,如何返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175165/

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