skip to Main Content

assume we have the following working directory, which is a local git repository

---project
__init__.py
   ---folder1 
      __init__.py
      functions.py 
   ---folder2
      __init__.py
      project.py

I use Visual Studio Code with the working directory based in the folder project. Assume project.py loads functions from functions.py which is in folder 1

import (some modules)
import folder1.functions

This throws a ModuleNotFoundError

If i work with Pycharm, it is possible to adjust the interpreter, such that the above error doesnt occure
For VS Code i added the current working directory, where python is looking for modules by adding the following

import sys 

sys.append('.')

This solves locally my problem, but assume you work on a larger project with a lot of modules and subfolders, and modules loading functions from other subfolder. That would imply that i have to add "import sys …" , into every python file existing in the git repository. Is there any easier solution? Like an option of Pycharm for VS Code?

2

Answers


  1. In order to get a similar behavior to Pycharm, you can create a workspace, edit its config and add the missing paths to the PYTHONPATH environment variables.
    For example in the file your_project.code-workspace, if you are on linux, add in the settings :

    "terminal.integrated.env.linux": {
                "PYTHONPATH": "${env:PYTHONPATH}:${workspaceFolder}/folder1:${workspaceFolder}/folder2"
            }
    

    Useful answer: How to correctly set PYTHONPATH for Visual Studio Code

    Login or Signup to reply.
  2. Usually, for the original problem. You can search Execute In File Dir in settings.

    If you uncheck it, VSCode will VSCode will have the workspace as the root directory.

    enter image description here

    It seems that there’s something wrong with this settings. I’ve submitted it to the github as a bug.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search