You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python自动创建激活虚拟环境及安装依赖(Windows)

解决虚拟环境初始化与VS Code自动切换解释器问题

一、跳过“激活”步骤,直接用虚拟环境内的Python执行依赖安装

你遇到的激活问题本质是:subprocess启动的子进程激活虚拟环境,不会影响父脚本的环境,而且Windows下直接调用Activate.ps1会触发默认关联程序(记事本)打开,根本没起到激活作用。正确的做法是直接调用虚拟环境内的Python解释器来执行pip安装,完全不需要激活:

import os
import subprocess

env_name = ".venv"
# 创建虚拟环境
subprocess.run(["python", "-m", "venv", env_name], check=True)

# 获取虚拟环境内Python的路径
if os.name == "nt":  # Windows系统
    venv_python = os.path.join(env_name, "Scripts", "python.exe")
else:  # Linux/macOS
    venv_python = os.path.join(env_name, "bin", "python")

# 升级pip并安装依赖(假设你有requirements.txt)
subprocess.run([venv_python, "-m", "pip", "install", "--upgrade", "pip"], check=True)
subprocess.run([venv_python, "-m", "pip", "install", "-r", "requirements.txt"], check=True)

这样直接用.venv/Scripts/python.exe执行pip,所有依赖都会安装到虚拟环境里,完全不需要激活操作。

二、修复Windows下Activate.ps1的执行问题(可选)

如果确实需要在脚本中触发PowerShell激活(比如后续要在同一个子shell里执行命令),需要明确调用PowerShell来运行脚本,同时临时放宽执行策略:

if os.name == "nt":
    activate_script = os.path.join(env_name, "Scripts", "Activate.ps1")
    # 用PowerShell执行激活脚本,Bypass策略允许运行本地脚本
    subprocess.run(
        ["powershell", "-ExecutionPolicy", "Bypass", "-Command", f". '{activate_script}' ; 你的后续命令"],
        shell=True,
        check=True
    )

注意:这种方式仅在当前subprocess的shell会话中生效,父脚本的环境还是系统Python。

三、自动配置VS Code解释器

VS Code通过.vscode/settings.json来保存默认解释器路径,脚本可以自动创建这个文件并写入配置:

# 创建.vscode目录(如果不存在)
vscode_dir = ".vscode"
if not os.path.exists(vscode_dir):
    os.makedirs(vscode_dir)

# 写入解释器配置
settings_path = os.path.join(vscode_dir, "settings.json")
# 转换路径为VS Code识别的格式(Windows下用正斜杠或双反斜杠)
formatted_python_path = venv_python.replace("\\", "/")

settings_content = f'''{{
    "python.defaultInterpreterPath": "{formatted_python_path}",
    "python.terminal.activateEnvironment": true
}}'''

with open(settings_path, "w", encoding="utf-8") as f:
    f.write(settings_content)

这样创建虚拟环境后,VS Code会自动读取这个配置,无需手动切换解释器。

四、完整脚本示例

把上面的逻辑整合起来,就是一个完整的first_setup.py:

import os
import subprocess

def main():
    env_name = ".venv"
    requirements_file = "requirements.txt"

    # 1. 创建虚拟环境
    print("创建虚拟环境...")
    subprocess.run(["python", "-m", "venv", env_name], check=True, capture_output=True)

    # 2. 获取虚拟环境Python路径
    if os.name == "nt":
        venv_python = os.path.join(env_name, "Scripts", "python.exe")
    else:
        venv_python = os.path.join(env_name, "bin", "python")

    # 3. 升级pip并安装依赖
    print("升级pip...")
    subprocess.run([venv_python, "-m", "pip", "install", "--upgrade", "pip"], check=True, capture_output=True)
    
    if os.path.exists(requirements_file):
        print("安装依赖...")
        subprocess.run([venv_python, "-m", "pip", "install", "-r", requirements_file], check=True)
    else:
        print(f"未找到{requirements_file},跳过依赖安装")

    # 4. 配置VS Code解释器
    print("配置VS Code解释器...")
    vscode_dir = ".vscode"
    if not os.path.exists(vscode_dir):
        os.makedirs(vscode_dir)
    
    settings_path = os.path.join(vscode_dir, "settings.json")
    formatted_python_path = venv_python.replace("\\", "/")
    settings_content = f'''{{
        "python.defaultInterpreterPath": "{formatted_python_path}",
        "python.terminal.activateEnvironment": true
    }}'''
    
    with open(settings_path, "w", encoding="utf-8") as f:
        f.write(settings_content)

    print("初始化完成!")

if __name__ == "__main__":
    main()

注意事项

  • 确保你的项目根目录下有requirements.txt,否则脚本会跳过依赖安装
  • Windows下如果遇到PowerShell执行权限问题,用户可以手动执行Set-ExecutionPolicy RemoteSigned(以管理员身份运行PowerShell),允许本地脚本运行

内容的提问来源于stack exchange,提问作者kry23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:45:30