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()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM