def download_file(url, path, filename): file_path = os.path.join(path, filename) try: response = requests.get(url, stream=True, headers={'Accept-Encoding': None}) total_size = int(response.headers.get('content-length', 0)) block_size = 1024*1024 progress = 0 progress_bar = [[sg.Text('正在更新:')], [sg.ProgressBar(total_size, orientation='h', size=(20, 20), key='progressbar')]] window = sg.Window('自动开票', progress_bar) with open(file_path, 'wb') as f: for data in response.iter_content(block_size): start_time = time.time() f.write(data) progress += len(data) print(progress) # 计算下载速度和调整块大小 duration = time.time()-start_time #print(duration) # 得到下载一个块的时间 if duration > 2 and progress > block_size: # 当下载时间大于2秒以及下载进度条足够 speed = block_size/duration # 计算下载平均速度 # 将下载速度赋值给block_size if block_size > int(speed): # 如果原始块的大小大于后面计算出来的块大小,则将原始块的大小改小,如果是小于还是原来的块大小 block_size = int(speed) start_time = time.time() elif duration < 1 and progress > block_size * 2: # 当下载时间小于1秒并且已经下载超过两个块的大小时,增加块大小 block_size *= 2 start_time = time.time() #print(block_size) # 判断取消事件 window.Read(timeout=0) if progress_bar: progress_bar = window['progressbar'] progress_bar.UpdateBar(progress) sg.Popup('更新完成') print(sg.Popup) window.close() except requests.exceptions.RequestException: sg.Popup('下载更新失败,请检查网络')将以上代码切换为ftp服务器下载文件,服务器地址wei81.68.182.121,用户名为cttest,密码为123
时间: 2024-03-07 11:48:18 浏览: 146
首先,你需要用Python中的ftplib库来连接FTP服务器并下载文件。以下是修改后的代码:
```
import ftplib
import os
import time
import PySimpleGUI as sg
def download_file(url, path, filename):
ftp = ftplib.FTP('81.68.182.121')
ftp.login(user='cttest', passwd='123')
ftp.cwd(path)
file_path = os.path.join(path, filename)
try:
total_size = ftp.size(filename)
block_size = 1024*1024
progress = 0
progress_bar = [[sg.Text('正在更新:')], [sg.ProgressBar(total_size, orientation='h', size=(20, 20), key='progressbar')]]
window = sg.Window('自动开票', progress_bar)
with open(file_path, 'wb') as f:
ftp.retrbinary('RETR {}'.format(filename), f.write, block_size)
progress += block_size
print(progress)
# 计算下载速度和调整块大小
duration = time.time()-start_time
#print(duration) # 得到下载一个块的时间
if duration > 2 and progress > block_size:
# 当下载时间大于2秒以及下载进度条足够
speed = block_size/duration # 计算下载平均速度
# 将下载速度赋值给block_size
if block_size > int(speed):
# 如果原始块的大小大于后面计算出来的块大小,则将原始块的大小改小,如果是小于还是原来的块大小
block_size = int(speed)
start_time = time.time()
elif duration < 1 and progress > block_size * 2:
# 当下载时间小于1秒并且已经下载超过两个块的大小时,增加块大小
block_size *= 2
start_time = time.time()
#print(block_size)
# 判断取消事件
window.Read(timeout=0)
if progress_bar:
progress_bar = window['progressbar']
progress_bar.UpdateBar(progress)
ftp.quit()
sg.Popup('更新完成')
window.close()
except ftplib.all_errors:
sg.Popup('下载更新失败,请检查网络或FTP服务器连接')
```
注意:这里我们用到了ftplib库来连接FTP服务器,ftp.retrbinary()方法用来下载文件,ftp.size()方法用来获取文件大小。
阅读全文