pycharm 项目,同版本解释器 venv 环境压缩包迁移、激活。
在 XX项目\venv 目录下创建脚本:Modify_venv.py
import os
import sys
import subprocess
import shutil
def update_activate():
current_dir = os.getcwd()
print("当前目录:", current_dir)
activate_path = os.path.join(current_dir, 'Scripts', 'activate.bat')
print("虚拟环境 activate.bat 路径:", activate_path)
backup_path = activate_path + ".bak"
shutil.copyfile(activate_path, backup_path)
with open(activate_path, 'r') as f:
lines = f.readlines()
new_venv_path = current_dir
print("修改虚拟环境路径为:", new_venv_path)
for i, line in enumerate(lines):
if line.startswith('set "VIRTUAL_ENV='):
lines[i] = f'set "VIRTUAL_ENV={new_venv_path}"\n'
with open(activate_path, 'w') as f:
f.writelines(lines)
def update_config():
config_path = os.path.join(os.getcwd(), 'pyvenv.cfg')
print("pyvenv.cfg 路径:", config_path)
backup_path = config_path + ".bak"
shutil.copyfile(config_path, backup_path)
config = {}
with open(config_path, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, value = line.split("=", 1)
config[key.strip()] = value.strip()
python_install_path = os.path.dirname(sys.executable)
print("修改 Python 安装路径为:", python_install_path)
config['home'] = python_install_path
config['base-prefix'] = python_install_path
config['base-exec-prefix'] = python_install_path
config['base-executable'] = os.path.join(python_install_path, 'python.exe')
with open(config_path, "w") as f:
for key, value in config.items():
# 直接将替换后的值写入文件中
f.write(f"{key}={value}\n")
def activate_virtualenv():
activate_path = os.path.join(os.getcwd(), 'Scripts', 'activate.bat')
print("执行虚拟环境激活:", activate_path)
process = subprocess.Popen(activate_path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 进行控制台进度输出
while True:
output = process.stdout.readline()
if output == b'' and process.poll() is not None:
break
if output:
print(output.strip().decode('utf-8'))
return_code = process.poll()
if return_code == 0:
print("虚拟环境激活成功!")
else:
print(f"虚拟环境激活失败,错误码为 {return_code}。")
if __name__ == '__main__':
update_activate()
update_config()
activate_virtualenv()