批处理进入python虚拟环境_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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值