如何修复VS Code中从项目上级目录调试Python模块时出现的ModuleNotFoundError
Fixing ModuleNotFoundError When Debugging Python Modules from Parent Directory in VS Code
Let's get this sorted out—your error happens because even though you set the working directory to the parent folder, Python's module search path (sys.path) doesn't automatically include that directory when launching via debugpy. Here's how to fix it:
Updated launch.json Configuration
Replace your existing config with this:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Debug Module from Parent", "type": "debugpy", "request": "launch", "module": "project_folder.folder1.main", "cwd": "${workspaceFolder}/..", "console": "integratedTerminal", "env": { "PYTHONPATH": "${workspaceFolder}/.." } } ] }
Key Changes & Explanations
- Added
envwithPYTHONPATH: This explicitly adds your project's parent directory to Python's module search path. Now debugpy can locate theproject_foldertop-level module without issues. - Verify
__init__.pyfiles: Make sure bothproject_folder/andproject_folder/folder1/contain an empty__init__.pyfile. While Python 3.3+ supports namespace packages without these files, debugpy sometimes relies on them to recognize the package structure during debugging.
Quick Validation Step
Before launching the debugger, open an integrated terminal in VS Code, navigate to your project's parent directory, and run:
python -m project_folder.folder1.main
If this runs successfully, the updated launch.json should work perfectly for debugging.
内容的提问来源于stack exchange,提问作者Lerck
相关产品推荐
相关产品推荐

