在Python中,可以使用第三方库ftplib
和tqdm
来查看FTP传输进度。以下是一个示例代码:
首先,确保已经安装了tqdm
库。如果没有安装,可以使用以下命令安装:
pip install tqdm
然后,使用以下代码实现FTP文件传输并显示进度:
from ftplib import FTP from tqdm import tqdm import os def ftp_upload(local_file, remote_file): # 连接到FTP服务器 ftp = FTP('ftp.example.com') ftp.login(user='username', passwd='password') ftp.set_pasv(True) # 被动模式 # 打开本地文件 with open(local_file, 'rb') as f: # 上传文件并显示进度 ftp.storbinary(f'STOR {remote_file}', tqdm(f, unit='B', unit_scale=True, desc=local_file)) # 关闭连接 ftp.quit() # 使用示例 local_file = 'path/to/local/file.txt' remote_file = 'path/to/remote/file.txt' ftp_upload(local_file, remote_file)
在这个示例中,我们定义了一个名为ftp_upload
的函数,它接受本地文件路径和远程文件路径作为参数。我们使用ftplib
库连接到FTP服务器,并使用tqdm
库创建一个进度条。storbinary
方法用于上传文件,同时tqdm
库会自动更新进度条。
请注意,您需要将示例代码中的ftp.example.com
、username
和password
替换为您自己的FTP服务器信息。