如何在VS Code的Python交互窗口中配置项目导入路径?
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:
1. Project-Specific .env with Workspace Variables (Recommended)
This avoids absolute paths and works across all VS Code contexts (interactive windows, terminal, tests, code analysis).
Create a
.envfile 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.envFileensures the .env settings apply to the interactive window and script cells.terminal.integrated.env.windowskeeps your terminal environment in sync.python.analysis.extraPathsfixes 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
.envfile in your user directory (e.g.,C:\Users\YourName\.envon 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

