如何为pysmb的SMB文件传输添加进度条(支持tqdm/alive_bar)
SMB文件传输添加进度条(tqdm/alive_bar实现)
核心思路
原代码使用storeFile一次性上传整个文件,无法跟踪进度。我们改用openFile获取远程文件的可写句柄,分块读取本地文件并逐块上传,同时用进度条工具统计已传输字节数。
使用tqdm实现进度条
import os from smb.SMBConnection import SMBConnection from tqdm import tqdm # 配置参数 local_file_path = 'file.txt' remote_share_name = 'Share' remote_file_path = 'file.txt' chunk_size = 1024 * 1024 # 1MB块大小,可根据网络情况调整 # 获取本地文件总大小 total_file_size = os.path.getsize(local_file_path) # 初始化SMB连接 conn = SMBConnection( username='Admin', password='Pa$$w0rd', my_name='', remote_name='PC', domain='WORKGROUP', use_ntlm_v2=True ) conn.connect(ip='192.168.10.10') try: # 分块上传并显示进度 with open(local_file_path, 'rb') as local_f, \ tqdm(total=total_file_size, unit='B', unit_scale=True, dynamic_ncols=True, desc='上传中') as progress_bar, \ conn.openFile(service_name=remote_share_name, path=remote_file_path, mode='w') as remote_f: while True: chunk = local_f.read(chunk_size) if not chunk: break remote_f.write(chunk) progress_bar.update(len(chunk)) finally: conn.close()
使用alive_bar实现进度条
import os from smb.SMBConnection import SMBConnection from alive_progress import alive_bar # 配置参数 local_file_path = 'file.txt' remote_share_name = 'Share' remote_file_path = 'file.txt' chunk_size = 1024 * 1024 # 1MB块大小 # 获取本地文件总大小 total_file_size = os.path.getsize(local_file_path) # 初始化SMB连接 conn = SMBConnection( username='Admin', password='Pa$$w0rd', my_name='', remote_name='PC', domain='WORKGROUP', use_ntlm_v2=True ) conn.connect(ip='192.168.10.10') try: # 分块上传并显示进度 with open(local_file_path, 'rb') as local_f, \ alive_bar(total_file_size, unit='B', scale='SI', title='上传进度') as progress_bar, \ conn.openFile(service_name=remote_share_name, path=remote_file_path, mode='w') as remote_f: while True: chunk = local_f.read(chunk_size) if not chunk: break remote_f.write(chunk) progress_bar(len(chunk)) finally: conn.close()
注意事项
chunk_size可根据网络带宽调整:带宽高可设为2MB/4MB,带宽低则设为512KB,平衡传输效率和内存占用。- 使用
try...finally保证SMB连接在异常情况下也能正常关闭,避免资源泄漏。 - 若需要覆盖远程已存在文件,
openFile的mode设为'w'即可(默认会覆盖);若要追加则设为'a'。
内容的提问来源于stack exchange,提问作者Alex Rebell
相关产品推荐
相关产品推荐

