3月31日【进度条控制】
3月31日【进度条控制】
一、简单版
# -* - coding: UTF-8 -* -
#filename jindutiao.py
#create by henryzkf 20180331 succ
import time
for i in range(10):
time.sleep(1) #每秒打印一次
print('#',end='-',flush=True) #end需要指定为空,否则每一行打印一个#;flush需要指定为True,才会立刻打印
二、复杂版
两个问题,第一个是导入requests报错,套路了,在python安装目录下 pip3 install requests
ImportError: No module named 'requests'
导入tqdm报错 pip3 install tqdm
运行后提示urlopen(url)报错,修改为urllib.request.urlopen(url)解决 附录代码
# -* - coding: UTF-8 -* -
#filename demo_jindutiao.py
#create by henryzkf 20180331 succ
import os
import urllib.request
import requests
from tqdm import tqdm
def download_from_url(url, dst):
"""
@param: url to download file
@param: dst place to put the file
"""
file_size = int(urllib.request.urlopen(url).info().get('Content-Length', -1))
if os.path.exists(dst):
first_byte = os.path.getsize(dst)
else:
first_byte = 0
if first_byte >= file_size:
return file_size
header = {"Range": "bytes=%s-%s" % (first_byte, file_size)}
pbar = tqdm(
total=file_size, initial=first_byte,
unit='B', unit_scale=True, desc=url.split('/')[-1])
req = requests.get(url, headers=header, stream=True)
with(open(dst, 'ab')) as f:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
pbar.update(1024)
pbar.close()
return file_size
if __name__ == '__main__':
url = "http://newoss.maiziedu.com/machinelearning/pythonrm/pythonrm5.mp4"
download_from_url(url, "./new.mp4")
浙公网安备 33010602011771号