pycharm 项目快速迁移脚本

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值