直接上代码罢。。。
import os
import re
def config():
# 修改pip国内镜像源
os.system('pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple')
def install(command):
os.system(command)
def get_result(command):
return os.popen(command).read()
# 检查str2是否在str中
def is_in(str,str2):
if re.findall(str2,str,re.IGNORECASE):
return True
else:
return False
# 检查是否已经安装某库,若未安装则安装
def check_install(list):
for i in list:
# 默认状态为未安装
flag = False
result = get_result('pip show ' + i)
for j in result.splitlines():
if is_in(j,'Version'):
print(i + ' is installed')
flag = True
break
if flag == False:
print(i + ' is not installed')
install('pip install ' + i)
print('')
print('package list:')
print(get_result('pip list'))
if __name__ == '__main__':
config()
list = [
'pygame',
'pyautogui',
'pyperclip',
'requests',
'pandas',
'numpy',
'matplotlib'
]
check_install(list=list)
大致思路:
- 修改镜像:可以直接用cmd命令操作
- get_result函数:使用popen()可以在执行cmd命令的同时,获取到返回的结果,返回的结果用来进行是否已经安装的判断
- is_in函数:判断一个字符串是否存在于另一个字符串当中,忽略大小写
- 根据pip show返回的结果的特征发现,若第三方库已经安装,则会显示第三方库的详细信息,其中的version就可以用来作为已安装的特征,只要判断返回的结果是否包含version,就可以知道是否已安装
注意点:不能直接把列表中的元素跟返回的pip list比较,因为名称可能会不同