Module not found in Python

2 weeks ago 10
ARTICLE AD BOX

When you run a python script, the interpreter makes some best guesses about the structure of your code base. Namely, where to search for additional user modules. It does this by assuming that the directory that contains the target script file is a root from which to search for other modules. This behaviour is not always desired. In your case, when you run python path/to/project/src/main.py it will add path/to/project/src as the directory to look for additional user modules. Meaning it cannot find lib.utils as the lib directory is located outside of the path/to/project/src directory. What you want is for the interpreter to look for additional modules in path/to/project. As such, you will have to make some changes to how you run your code. The three options are:

Use the PYTHONPATH environment variable Use the -m switch Create a main.py shim in your project root.

This is an environment variable that tells Python where to search for modules. Its form is a colon (:) separated list of directories to search for modules.

export PYTHONPATH=/path/to/projectA:/path/to/projectB`

In your scenario you might do (using a posix shell):

export PYTHONPATH=/path/to/project python src/main.py

When using the -m switch, the default behaviour is to add the current working directory to its list of directories to search for user modules. So, from the path/to/project directory you would run the command python -m src.main. This would add path/to/project to the list of directories to search, meaning both the src package and the lib package can be found. The interpreter will then attempt to find a module called src.main and execute it as the __main__ module.

With a shim, you add a simple file in your project root that imports your main function and calls it. As the shim file is in your project root, the project root will be added to the list of directories to search for modules, and so both your src and lib packages can be found. For example:

project/main.py

from src.main import main if __name__ == '__main__': main()

NB. The actual name of the shim file (other than the .py suffix) is not important.

Finally, these solutions are all agnostic to how you run your python code. You'll need to figure out how to make make these setting changes in VS Code yourself. As such, using the shim might be the easiest method to get working.

Read Entire Article