pythonvisual-studio-codepackagerelative-import

How to import a file from one package into another in Python without using sys.path.append(...) in Visual Studio Code?


I am working on a Python project using Visual Studio Code (VSC) and have the following folder structure:

Python  
├──.vscode  
│   └── launch.json  
├── package1  
│   ├── __init__.py  
│   └── module1.py  
├── package2  
│   ├── __init__.py  
│   └── module2.py  
└── Python.code-workspace

I want to import module1.py from package1 into module2.py in package2. However, I'm facing difficulties getting the import statement to work correctly without using sys.path.append(...).

Here's the import statement I've tried in module2.py: from package1 import module1

However, when I run the code, I receive an ImportError stating that the module cannot be found. I have verified that both packages have an __init__.py file.

I have also tried modifying the launch.json file in VSC to set the PYTHONPATH and avoid using sys.path.append(...), but the import still fails. Here's my current launch.json configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python Launch",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/package2/module2.py",
      "cwd": "${workspaceFolder}/package2",
      "env": {
        "PYTHONPATH": "${workspaceFolder}"
      }
    }
  ]
}

I would appreciate any guidance or suggestions on how to properly import a file from one package into another without relying on sys.path.append(...) and considering the project structure in Visual Studio Code.


Solution

  • After configuring launch.json, you need to use the green triangle button to debug the script in the Run and Debugging panel or use Start Debugging or Run Without Debugging under the Run menu to debug or execute the script. The above method will use the configuration in launch.json.

    enter image description here

    If you use the upper right triangle button to execute the script, this will not load the configuration in launch.json.

    enter image description here

    The same file structure as yours, the effect of using Run --> Run Without Debugging.

    enter image description here

    Using the display launch.json in your question can also run successfully.

    Another way is to add the .env file under the python folder

    enter image description here

    Then use Run --> Run Without Debugging to execute moudle2.py