python 通过执行脚本安装库或卸载库
import subprocess
import sysdef install_package(package):try:# 检查库是否已安装subprocess.check_call([sys.executable, '-m', 'pip', 'show', package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)print(f"{package} 已安装,无需操作。")except subprocess.CalledProcessError:print(f"正在安装 {package}...")subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])print(f"{package} 安装成功。")def uninstall_package(package):try:# 检查库是否已安装subprocess.check_call([sys.executable, '-m', 'pip', 'show', package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)print(f"正在卸载 {package}...")subprocess.check_call([sys.executable, '-m', 'pip', 'uninstall', package, '-y'])print(f"{package} 卸载成功。")except subprocess.CalledProcessError:print(f"{package} 未安装,无需卸载。")if __name__ == '__main__':# 要安装的库列表packages_to_install = ['openpyxl==3.1.3', 'xlrd', 'xlwt']# 安装库for package in packages_to_install:install_package(package)print("所有库安装完成。")# 要卸载的库列表# packages_to_uninstall = ['openpyxl', 'xlrd', 'xlwt']## # 安装库# for package in packages_to_uninstall:# uninstall_package(package)## print("所有库卸载完成。")
可以看到列表其中一个库安装好了
可以看到库被卸载了