python 创建虚拟环境:bat实现一键
1.New a python project
2.cd %project.home%切换到项目根目录
3.运行setup.bat创建venv虚拟环境 (注意内网运行setup.bat需要手动将requirements.txt需要的安装包下载下到dependency目录(pip download -d ./dependency -r requirements.txt),外网直接运行)
4。等待安装结束重新打开project环境默认引用了interpreter无异常显示,否则手动配置刚才创建的venv/Scripts/python.exe;
5.注意setup.bat 和denpendency文件夹,fit_env_dir.py以及requirements.txt 都必须在project根目录下
setup.bat
@echo off echo "start check requirements.txt file" if exist %cd%\requirements.txt ( echo "check requirements.txt finish" ) else ( echo "not exist requirements.txt" ) echo "start init env" SET curdir=%cd%\venv echo %curdir% if exist %curdir% ( RD /S /q %cd%\venv echo "delete old venv" TIMEOUT /T 8 echo "start create new venv" python -m venv ./venv TIMEOUT /T 5 echo "create new venv finish" ) else ( python -m venv ./venv echo "finish create venv" ) call %cd%\venv\Scripts\activate.bat echo "source env finish" echo "pwd is : %cd%" if exist %cd%\dependency ( ::"delete old dependency" ::RD /S /q %cd%\dependency echo "have exist dependency" TIMEOUT /T 8 md dependency echo "finish new dependency dir create" ) else ( md dependency echo "create dependency dir finish" ) echo "start download pack into dependency" pip download -d ./dependency -r requirements.txt pip install --no-index --ignore-installed --find-links=./dependency -r requirements.txt echo "install packages flowing:" pip list deactivate echo "exit env virtual" echo "wait 10 seconds...." TIMEOUT /T 5 python -m %cd%\fit_env_dir.py echo "pyhton3 fit envdir finish" TIMEOUT /T 10
3.fit_env_dir.py:
import os,re def fit_activate_bat(): with open(os.getcwd()+"\\venv\\Scripts\\activate.bat","r+")as f: strings=f.readlines() for index,line in enumerate(strings): if line.__contains__("VIRTUAL_ENV="): res=re.findall('VIRTUAL_ENV=(.*)"',line)[0] strings[index]=line.replace(res,os.getcwd()+"\\venv") with open(os.getcwd() + "\\venv\\Scripts\\activate.bat", "w+",encoding="utf-8")as h: h.writelines(strings) def fit_Activateps1(): with open(os.getcwd()+"\\venv\\Scripts\\Activate.ps1","r+",encoding="utf-8")as e: lines=e.readlines() for index, line in enumerate(lines): if line.__contains__("env:VIRTUAL_ENV="): res = re.findall('env:VIRTUAL_ENV="(.*)"', line)[0] lines[index] = line.replace(res, os.getcwd() + "\\venv") with open(os.getcwd() + "\\venv\\Scripts\\Activate.ps1", "w+", encoding="utf-8")as g: g.writelines(lines) def all_fit(): fit_activate_bat() fit_Activateps1() if __name__ == '__main__': all_fit()