Home > Enterprise >  VS Code does not find own python module in Workspace
VS Code does not find own python module in Workspace

Time:06-22

I am working on a python package with VS Code with the following layout of the opened workspace folder in VS Code

workspace
|   tests
| | - test1.py
| |   other_tests
| | | - test2.py 
|   mymodule
| | ...

What I want is to call in test1.py and test2.py the package mymodule with

import mymodule

When I do this, I always get the error no module named 'mymodule'. I know i can load the path via inserting the following to all test files:

import sys
sys.path.append('<path_to>/workspace/')

Then mymodule is correctly loaded. (I know I can use pathlib.Path(__file__).parent[n] for some n to get <path_to>.

But this process is really cumbersome if you have many test files in different folders... and it is just ugly.

Is there any way, to tell VS Code to always include the workspace in the path?

I tried a .env file with

PYTHONPATH=<path_to>/workspace/

and I also tried to add the following to launch.json:

"env": { "PYTHONPATH": "${workspaceFolder}" }

Both did not do the trick. (I am also not sure if PYTHONPATH is at all the right solution to my problem, i just tried it ^^).

In short:

I would like to tell VS Code, that it should always include workspace to the search path whenever a python function tries to load a module, regarding the location of the function, so I do not have to call sys.path.append('<path_to>/workspace/') in every single main file.

CodePudding user response:

Option #1 (Recommended): Split into a separate package

Since what you are basically looking for is to have mypackage as a full-blown package accessible to all the code in this environment, why not do that?

Just separate mypackage into a separate pip package, and then "install" it using pip into a virtual environment that you are using within this project.

Option #2: Use PYTHONPATH

From Python's enter image description here

I am using a virtual environment

  • Related