gpt4 book ai didi

python - 下载文件时 urlretrieve 挂起

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:27 25 4
gpt4 key购买 nike

我有一个非常简单的脚本,它使用 urllib 检索一个 zip 文件并将其放在我的桌面上。该 zip 文件只有几 MB,下载时间不长。但是,脚本似乎并没有完成,它只是挂起。有没有办法强制关闭urlretrieve?...或者更好的解决方案?

该 URL 为公共(public) ftp 大小。 ftp 可能是原因吗?

我正在使用 python 2.7.8。

url = r'ftp://ftp.ngs.noaa.gov/pub/DS_ARCHIVE/ShapeFiles/IA.ZIP'
zip_path = r'C:\Users\***\Desktop\ngs.zip'

urllib.urlretrieve(url, zip_path)

提前致谢!

---编辑---

能够使用 ftplib 完成任务...

import os
from ftplib import FTP
import zipfile

ftp_site = 'ftp.ngs.noaa.gov'
ftp_file = 'IA.ZIP'
download_folder = '//folder to place file'
download_file = 'name of file'
download_path = os.path.join(download_folder, download_file)

# Download file from ftp
ftp = FTP(ftp_site)
ftp.login()
ftp.cwd('pub/DS_ARCHIVE/ShapeFiles') #change directory
ftp.retrlines('LIST') #show me the files located in directory
download = open(download_path, 'wb')
ftp.retrbinary('RETR ' + ftp_file, download.write)
ftp.quit()
download.close()

# Unzip if .zip file is downloaded
with zipfile.ZipFile(download_path, "r") as z:
z.extractall(download_folder)

最佳答案

urllib 对错误捕获和调试的支持非常差。 urllib2 是一个更好的选择。 urllib2 中的 urlretrieve 等价物是:

resp = urllib2.urlopen(im_url)
with open(sav_name, 'wb') as f:
f.write(resp.read())

要捕获的错误是:

urllib2.URLError, urllib2.HTTPError, httplib.HTTPException

如果网络中断,您还可以捕获 socket.error。

关于python - 下载文件时 urlretrieve 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164813/

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