前言:
基于 system 与 executable 的模块便捷安装
利用 python 中的异常检测 实现 ---->> try...except
# -*- coding:UTF-8 -*-
try:
import re
from bs4 import BeautifulSoup
from icecream import ic
import pyqt5
except ImportError as error:
from re import search
from os import system
from sys import executable
system('{} -m pip install {} -i https://pypi.tuna.tsinghua.edu.cn/simple'
.format(executable, search("'(.*?)'", str(error))[1]))
代码详解
# -*- coding:UTF-8 -*-
try:
# 导入需要加载,但是没有安装的模块
import pyqt5
except ImportError as error: # 检测(模块未安装)异常
# 导入用于检测的标准库
from re import search # search 用来查找相关的字符串
from os import system # system 用于调动命令窗口,或者bash进程 执行语句
from sys import executable # executable 用于获取当前环境下解释器的绝对路径
# 代码实现
"""
基于 pip install packname -i 镜像url
--使用 format 拼接代码
--引用清华源
--将异常转换为字符串类型, 作为正则表达式的索引文本
--使用表达式进行模式匹配 -->> "'(.*?)'"
--通过executable 获取当前解释器的路径,确保安装的路径没有错误
"""
system('{} -m pip install {} -i https://pypi.tuna.tsinghua.edu.cn/simple'
.format(executable, search("'(.*?)'", str(error))[1]))