Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode ModuleNotFoundError: No module named X

I am trying to build a new package, however, when I try to run any of the files from inside VSCode or from terminal, I am coming across this error:

ModuleNotFoundError: No module name 'x'

My current folder structure is as follows:

package
|---module
|------__init__.py
|------calculations.py
|------miscfuncs.py
|---tests
|------__init__.py
|------test_calcs.py
|---setup.py
|---requirements.txt

However, when I run my tests (PyTest) through VSCode and using import module.calculations as calc or from module.calculations import Class in test_calcs.py, the tests work as expected - which is confusing me.

I know this is a commonly asked question, but I cannot fathom out a solution that will work here.

I have tried checking the working directory is in system path using the code below. The first item on the returned list of directories is the one I am working in.

import sys
print(sys.path)

I have also used the following in the files to no avail:

import module.calculations 
import .module.calculations
from . import miscfuncs

When trying import .module.calculations, I get the following:

ModuleNotFoundError: No module named '__main__.module'; '__main__' is not a package

When trying from . import miscfuncs in calculations.py, I get the following error:

ImportError: cannot import name 'miscfuncs'

When working on a file within the module folder, I can use a relative import: import calculations and it works fine. This is fine for files within module, but not when I am working in test_calcs.py.

In my setup.py, I have a line for:

packages=['module']

Happy to post more info if required or a link to my repo for the full code.

EDIT

Following remram's solution:

I have updated launch.json to include the CWD and PYTHONPATH variables.

The module name is still not recognised, however, IntelliSense within VSCode is picking up the functions within the imported file just fine.

"version": "0.2.0",
"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
        "cwd": "${workspaceFolder}",
        "env": {"PYTHONPATH": "${cwd}"
        }
    }
    ]
like image 447
rockdoctor Avatar asked Oct 16 '22 02:10

rockdoctor


1 Answers

Make sure you are running from the package folder (not from package/module) if you want import module.calculations to work. You can also set the PYTHONPATH environment variable to the path to the package folder.

like image 96
remram Avatar answered Nov 30 '22 09:11

remram