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

如何在VS Code的Python交互窗口中配置项目导入路径?

Fixing Python Path Issues for Interactive Windows & Script Cells in VS Code

I’ve run into this exact problem before—getting the project root added to sys.path consistently across scripts, tests, and VS Code’s interactive window can be tricky. Here are the best no-source-modification solutions that work reliably:

This avoids absolute paths and works across all VS Code contexts (interactive windows, terminal, tests, code analysis).

  • Create a .env file in your project root with this line:

    PYTHONPATH=${PYTHONPATH}:${workspaceFolder}
    

    The ${workspaceFolder} variable is automatically replaced by VS Code with your project’s root directory, so no hardcoding paths needed.

  • Open your VS Code workspace settings (File > Preferences > Settings > Workspace tab) and add these entries:

    {
      "python.envFile": "${workspaceFolder}/.env",
      "terminal.integrated.env.windows": {
        "PYTHONPATH": "${workspaceFolder}:${env:PYTHONPATH}"
      },
      "python.analysis.extraPaths": ["${workspaceFolder}"]
    }
    
    • python.envFile ensures the .env settings apply to the interactive window and script cells.
    • terminal.integrated.env.windows keeps your terminal environment in sync.
    • python.analysis.extraPaths fixes code linting and intellisense issues.

After setting this up, restart VS Code or reload the window (Ctrl+Shift+P > Reload Window) to apply the changes. Your mypackage should now import correctly in #%% cells.

2. Global Setup (For All Projects)

If you want a Spyder-like default where every project’s root is automatically added to sys.path, you can use a user-level .env file:

  • Create a .env file in your user directory (e.g., C:\Users\YourName\.env on Windows) with:
    PYTHONPATH=${PYTHONPATH}:${workspaceFolder}
    
  • In your VS Code user settings (File > Preferences > Settings > User tab), set:
    {
      "python.envFile": "${userHome}/.env"
    }
    

This will add the root of any open workspace to your Python path by default. Note that this might cause conflicts if you have projects with similarly named packages, so use this cautiously.

3. Verify the Setup

To confirm everything is working as expected, run this in an interactive cell:

import sys
print(sys.path)

You should see your project root directory listed in the output.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:37:47