通过代码(python)直接设置vscode的源路径
将代码后面的:

SOURCE_PATH = r"D:\github\ubc"

改成需要设置的源路径,重启vscode即可完成源路径的配置

import os
import json
import platform


def set_vscode_python_source_path(target_path):
    vscode_dir = ".vscode"
    settings_file = os.path.join(vscode_dir, "settings.json")
    launch_file = os.path.join(vscode_dir, "launch.json")
    env_file = ".env"

    if not os.path.exists(vscode_dir):
        os.makedirs(vscode_dir)

    # --- Step A: Configure .env file ---
    env_lines = []
    if os.path.exists(env_file):
        with open(env_file, "r", encoding="utf-8") as f:
            env_lines = f.readlines()

    pythonpath_found = False
    new_env_lines = []
    path_sep = ";" if platform.system() == "Windows" else ":"

    for line in env_lines:
        if line.startswith("PYTHONPATH="):
            pythonpath_found = True
            current_path = line.strip().split("=", 1)[1]
            if target_path not in current_path:
                line = f"PYTHONPATH={current_path}{path_sep}{target_path}\n"
        new_env_lines.append(line)

    if not pythonpath_found:
        new_env_lines.append(f"PYTHONPATH={target_path}\n")

    with open(env_file, "w", encoding="utf-8") as f:
        f.writelines(new_env_lines)
    print(f"✅ [1/3] Updated runtime environment variable file: {os.path.abspath(env_file)}")

    # --- Step B: Configure settings.json (Core! Includes terminal environment variable injection) ---
    settings = {}
    if os.path.exists(settings_file):
        try:
            with open(settings_file, "r", encoding="utf-8") as f:
                content = f.read().strip()
                if content:
                    settings = json.loads(content)
        except json.JSONDecodeError:
            print(f"⚠️ Warning: {settings_file} format is incorrect, it will be regenerated.")

    # 1. Inject code completion path
    keys_to_update = ["python.analysis.extraPaths", "python.autoComplete.extraPaths"]
    for key in keys_to_update:
        if key not in settings:
            settings[key] = []
        if target_path not in settings[key]:
            settings[key].append(target_path)

    # 2. Tell VS Code basic run to read .env
    settings["python.envFile"] = "${workspaceFolder}/.env"

    # 3. Ultimate move: Directly force inject PYTHONPATH into the Windows VS Code terminal
    if "terminal.integrated.env.windows" not in settings:
        settings["terminal.integrated.env.windows"] = {}

    current_term_path = settings["terminal.integrated.env.windows"].get("PYTHONPATH", "")
    if target_path not in current_term_path:
        if current_term_path:
            settings["terminal.integrated.env.windows"]["PYTHONPATH"] = (
                f"{current_term_path};{target_path}"
            )
        else:
            settings["terminal.integrated.env.windows"]["PYTHONPATH"] = target_path

    with open(settings_file, "w", encoding="utf-8") as f:
        json.dump(settings, f, indent=4, ensure_ascii=False)
    print(
        f"✅ [2/3] Updated VS Code settings (including terminal environment forced injection): {os.path.abspath(settings_file)}"
    )

    # --- Step C: Configure launch.json (For F5 debugging) ---
    launch_data = {}
    if os.path.exists(launch_file):
        try:
            with open(launch_file, "r", encoding="utf-8") as f:
                content = f.read().strip()
                if content:
                    launch_data = json.loads(content)
        except json.JSONDecodeError:
            launch_data = {}

    if not launch_data:
        launch_data = {"version": "0.2.0", "configurations": []}
    elif "configurations" not in launch_data:
        launch_data["configurations"] = []

    config_exists = False
    for config in launch_data["configurations"]:
        if config.get("name") == "Python: Current File" and config.get("type") == "python":
            config["envFile"] = "${workspaceFolder}/.env"
            config_exists = True
            break

    if not config_exists:
        launch_data["configurations"].append(
            {
                "name": "Python: Current File",
                "type": "python",
                "request": "launch",
                "program": "${file}",
                "console": "integratedTerminal",
                "envFile": "${workspaceFolder}/.env",
            }
        )

    with open(launch_file, "w", encoding="utf-8") as f:
        json.dump(launch_data, f, indent=4, ensure_ascii=False)
    print(f"✅ [3/3] Updated VS Code F5 debugging file: {os.path.abspath(launch_file)}")

    print(f"\n🎉 Configuration script finished running!")
    print(
        "⚠️ EXTREMELY IMPORTANT: Be sure to click the [Trash Can Icon] in the upper right corner of the VS Code terminal panel at the bottom to completely close the old terminal! Then rerun your code."
    )


if __name__ == "__main__":
    # The correct level containing ipkiss has been set here for you
    SOURCE_PATH = r"D:\github\ubc"

    set_vscode_python_source_path(SOURCE_PATH)

更多推荐