代码来了:
def convert_seconds(seconds:'数字, 秒'):
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
M, d = divmod(d, 30) # 以每月 30 天计时
y, M = divmod(d, 365) # 以每年 365 天计时
if y > 0:
return '%d 年 %d 个月 %d 天零 %02d:%02d:%05.2f' % (y, M, d, h, m, s)
elif M > 0:
return '%d 个月零 %d 天 %02d:%02d:%05.2f' % (M, d, h, m, s)
elif d > 0:
return '%d 天零 %02d:%02d:%05.2f' % (d, h, m, s)
elif h > 0:
return '%02d:%02d:%05.2f' % (h, m, s)
elif m > 0:
return '%d 分 %.2f 秒' % (m, s)
else:
return '%.2f 秒' % s
def upgradePip(file:'文件名,从文件获取待安装插件列表' = ''):
from os import system, popen
from time import perf_counter, strftime, localtime, time
start = perf_counter()
if len(file)>0: # 安装由 pip freeze>pipList.txt 命令生成的 pipList.txt 插件列表文件
print('开始安装 pip 插件...\n当前时间:{}'.format(strftime('%Y-%m-%d %X', localtime(time()))))
system('python -m pip install -U pip')
with open(file, 'r') as f:
lines = f.readlines()
for l in lines:
x = l.split('==')[0]
if x == 'pip': continue
system('pip install ' + x)
else:
print('开始更新 pip 插件...\n当前时间:{}'.format(strftime('%Y-%m-%d %X', localtime(time()))))
with popen('pip list -o') as out:
tmp = out.buffer.read().decode('utf8')
if len(tmp) == 0:
print('\n今日 pip 插件无更新。\n')
else:
if tmp.find('pip ')>0:
system('python -m pip install -U pip')
else:
i = 0
for l in tmp.split('\n'):
i += 1
x = l.split(' ')[0]
if x == 'pip': continue
if i > 2 and len(l) > 0:
system('pip install -U ' + x)
system('pip freeze>pipList.txt')
end = perf_counter() - start
print('耗时:{}'.format(convert_seconds(end)))
upgradePip()
说明:
1、第一个函数 convert_seconds 用于计算并返回耗时;
2、第二个函数 upgradePip 为主函数;
3、入参后的冒号“:”是该参数的注释,后边的等号“=”是该参数的默认值;
4、入参 file 如果是文件名,用于新环境的插件迁移。如果为空,则更新当前环境插件;
5、file 是全路径文件名,由 pip freeze>pipList.txt 命令生成的 pipList.txt 插件列表文本文件。
6、行:
system('pip freeze>pipList.txt')
在当前路径下备份生成最新版本的插件列表文件,用于新环境的部署或分发。