Skip to content

Commit 3f69bcf

Browse files
authoredAug 22, 2022
Update get.py to support python 3.10+ (espressif#7166)
* Update get.py to support python 3.10+ * Use try/except to remove version check
1 parent 3ebb774 commit 3f69bcf

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed
 

‎tools/get.py

+42-5
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,17 @@ def mkdir_p(path):
5454

5555
def report_progress(count, blockSize, totalSize):
5656
if sys.stdout.isatty():
57-
percent = int(count*blockSize*100/totalSize)
58-
percent = min(100, percent)
59-
sys.stdout.write("\r%d%%" % percent)
57+
if totalSize > 0:
58+
percent = int(count*blockSize*100/totalSize)
59+
percent = min(100, percent)
60+
sys.stdout.write("\r%d%%" % percent)
61+
else:
62+
sofar = (count*blockSize) / 1024
63+
if sofar >= 1000:
64+
sofar /= 1024
65+
sys.stdout.write("\r%dMB " % (sofar))
66+
else:
67+
sys.stdout.write("\r%dKB" % (sofar))
6068
sys.stdout.flush()
6169

6270
def unpack(filename, destination):
@@ -82,6 +90,32 @@ def unpack(filename, destination):
8290
shutil.rmtree(rename_to)
8391
shutil.move(dirname, rename_to)
8492

93+
def download_file_with_progress(url,filename):
94+
import ssl
95+
import contextlib
96+
ctx = ssl.create_default_context()
97+
ctx.check_hostname = False
98+
ctx.verify_mode = ssl.CERT_NONE
99+
with contextlib.closing(urlopen(url,context=ctx)) as fp:
100+
total_size = int(fp.getheader("Content-Length",fp.getheader("Content-length","0")))
101+
block_count = 0
102+
block_size = 1024 * 8
103+
block = fp.read(block_size)
104+
if block:
105+
with open(filename,'wb') as out_file:
106+
out_file.write(block)
107+
block_count += 1
108+
report_progress(block_count, block_size, total_size)
109+
while True:
110+
block = fp.read(block_size)
111+
if not block:
112+
break
113+
out_file.write(block)
114+
block_count += 1
115+
report_progress(block_count, block_size, total_size)
116+
else:
117+
raise Exception ('nonexisting file or connection error')
118+
85119
def download_file(url,filename):
86120
import ssl
87121
import contextlib
@@ -126,8 +160,11 @@ def get_tool(tool):
126160
if is_ci:
127161
download_file(url, local_path)
128162
else:
129-
urlretrieve(url, local_path, report_progress)
130-
sys.stdout.write("\rDone\n")
163+
try:
164+
urlretrieve(url, local_path, report_progress)
165+
except:
166+
download_file_with_progress(url, local_path)
167+
sys.stdout.write("\rDone \n")
131168
sys.stdout.flush()
132169
else:
133170
print('Tool {0} already downloaded'.format(archive_name))

0 commit comments

Comments
 (0)
Please sign in to comment.