micropython 实现文件下载保存到本地
import sys
import gc
import ussl
import usocket
gc.collect()
debug = False
index_urls = ["https://micropython.org/pi", "https://pypi.org/pypi"]
install_path = None
cleanup_files = []
file_buf = bytearray(512)
warn_ussl = True
def url_open(url):
global warn_ussl
if debug:
print(url)
proto, _, host, urlpath = url.split("/", 3)
try:
if proto == "https:":
port = 443
else:
port = 80
if ":" in host:
host, port = host.split(":")
port = int(port)
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
except OSError as e:
fatal("Unable to resolve %s (no Internet?)" % host, e)
print("Address infos:", ai)
ai = ai[0]
s = usocket.socket(ai[0], ai[1], ai[2])
try:
# print("Connect address:", addr)
s.connect(ai[-1])
if proto == "https:":
s = ussl.wrap_socket(s, server_hostname=host)
if warn_ussl:
print("Warning: %s SSL certificate is not validated" % host)
warn_ussl = False
# MicroPython rawsocket module supports file interface directly
s.write("GET /%s HTTP/1.0\r\nHost: %s:%s\r\n\r\n" % (urlpath, host, port))
l = s.readline()
protover, status, msg = l.split(None, 2)
if status != b"200":
if status == b"404" or status == b"301":
raise NotFoundError("Package not found")
raise ValueError(status)
while 1:
l = s.readline()
if not l:
raise ValueError("Unexpected EOF in HTTP headers")
if l == b"\r\n":
break
except Exception as e:
s.close()
raise e
return s
def download(url,fname=None,length=512):
file_buf = bytearray(length)
downloadfile=url_open(url)
if not fname:
fname=url.split('/')[-1]
with open(fname, "wb") as outf:
while True:
sz = downloadfile.readinto(file_buf)
if not sz:
break
outf.write(file_buf, sz)
def fatal(msg, exc=None):
print("Error:", msg)
if exc and debug:
raise exc
sys.exit(1)
#cc=url_open("http://app.xb6.cn/home/api")
download("https://www.west.cn/images2016/logo.jpg",'/img/l.jpg')download("https://www.west.cn/images2016/logo.jpg",'/img/l.jpg') 第一个参数为下载地址 第二个参数为本地保存位置


支付宝打赏
微信打赏 


