文件上傳下載時,需要用到進度條顯示,代碼如下:
#!/usr/bin/python3
import sys
def humanbytes(B):
'Return the given bytes as a human friendly KB, MB, GB, or TB string'
B = float(B)
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) # 1,073,741,824
TB = float(KB ** 4) # 1,099,511,627,776
if B < KB:
return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')
elif KB <= B < MB:
return '{0:.2f} KB'.format(B/KB)
elif MB <= B < GB:
return '{0:.2f} MB'.format(B/MB)
elif GB <= B < TB:
return '{0:.2f} GB'.format(B/GB)
elif TB <= B:
return '{0:.2f} TB'.format(B/TB)
def progres(num, Sum):
"""
顯示上傳進度條
num:已上傳大小
Sum:文件總大小
#l:定義進度條大小
"""
bar_length = 50 # 定義進度條大小
percent = float(num) / float(Sum)
hashes = '=' * int(percent * bar_length) # 定義進度顯示的數量長度百分比
spaces = ' ' * (bar_length - len(hashes)) # 定義空格的數量=總長度-顯示長度
sys.stdout.write(
"\r傳輸中: [%s] %d%% %s/%s " % (hashes + spaces, percent * 100, humanbytes(num), humanbytes(Sum))) # 輸出顯示進度條
sys.stdout.flush() # 強制刷新到屏幕