VSCode Python error in importing modules from subdirectories - python

My project file structure is like this,
project/src/test/myscript.py
project/src/utils/file_utils.py
When I run myscript.py, which has from utils import file_utils, it gave me error:
ModuleNotFoundError: No module named 'utils'
Previously in Pycharm IDE I did not get this type of error (maybe due to _ init _.py), the subdirs of the same parent dir could be detected. But not sure for VSCode, is there something I need to add for specifying the file structure? And I opened the folder project as my VSCode workspace (not sure if where I open the workspace matters)
I tried adding:
in the /project/.vscode/launch.json
"cwd": "${workspaceFolder}/src"
or in the begining of myscript.py
import sys
import os
src_path = os.path.dirname(os.path.abspath('/project/src/'))
sys.path.insert(0, src_path)
But none of them works. Does anyone have any insights? Thank you very much!

You could consider placing a .env file at the root of your project which adds your source directory to PYTHONPATH. i.e. something like
>>> cat /project/.env
PYTHONPATH=/project/src/
>>>
Your code will look a smidgen nicer without the explicit manipulation of sys.path.
VSCode's usage of .env files is documented here.

Yes, in Pycharm you didn't get this error because it adds __init__.py file automatically when you create a python module. The python identifies the structure of your project through these files, if your folder does not have __init__.py python will understand it as just any folder.

Unlike pycharm, vscode uses the workspace as the root directory to retrieve files. The first method you try is to write it in the launch.json file, which is applicable to debug rather than running it directly. You can use the following code to import:
from src.utils import file_utils

Related

Unable to import from a own modul

this is my first question and I searched the whole internet for one day and couldn't find a solution.
Hopefully someone can help me here.
I have running Anaconda and Python 3.8.3 64-bit on Windows 10.
I want to import an own program modul from an other file in an other folder .
foldera contains a testa.py file
folderb contains a testb.py file. I want to import foldera.testa
The import does not work. Terminal says ModuleNotFoundError: No module named
VS Code Screenshot
What I tryed:
put the file: __init__.py and .envin every project folder.
Reinstalling both programs and deleted temp files
Looking folder .vscode into settings.json showed that the python.pythonPath is set correctly to python.exe
Typed in python.exe sys.path.append('\\path\\to\\whatever')
and os.environ['PYTHONPATH'] = '\\path\\to\\whatever'
Thank you in advance for the help
Best regards
Sepp
I create a project with the same folder structure as yours, like the following screenshot shows:
In launch.json, you should add
"cwd": "${workspaceFolder}",
when testb.py looks for the module, this setting makes it first to search in the current workspace folder, and the code sys.path.append("./") let it turn to its parent directory, now testb.py is at the same level as foldera, so you can use import foldera.testa without any errors.

Python ModuleNotFoundError when not in working directory; getcwd finds module

When I try to run a python file with python3.6 src/main.py (the working directory is one above src) there's this error when importing another module from path src:
from src import another_module
ModuleNotFoundError: No module named 'src'
When I do
print(os.getcwd())
print(os.listdir(os.getcwd()))
I get what's expected:
path/to/working/directory
['src']
The import works when I run the script with PyCharm, but I need to run it outside PyCharm.
To make src a package, make an empty file named src/__init__.py
When you run a python script on the command line, the script's directory (which may not be the same as your shell current working directory) is added to the path.
So, since src/ is already in your path, you can just say import another_module.
Solved by creating another file run.py in the working directory that calls src/main.py and running run.py from the command line instead of src/main.py.
In launch.json, add the following line to your deployment:
"env": {"PYTHONPATH": "${workspaceRoot}"}
This seems to force Python to evaluate imports relative to the ${workingSpaceRoot} folder; allowing you to use a fully qualified name: from src import ...
The default behavior is to evaluate namespaces relatively. So, your original statement: from src import ... is actually looking in src/src/....
(Credit to #g4th who posted this solution on another StackOverflow page.)

Can't import own Python module

I am currently running on python 3.6 on anaconda. I have a project structure where (test/lib/yolo/yolo_model.py) and (test/car/detection/cpu_yolo_detector.py).
I run my main from the test directory. My main now calls the script cpu_yolo_detector.py from withing (test/car/detection).
From cpu_yolo_detector.py I want to access the yolo_model.py with
"from lib.yolo.yolo_model import YoloModel"
but I get "no module named lib.yolo".
At the beginning of the main.py I add ('C:\\Users\\Name\\Desktop\\test\\lib\\yolo') to the sys.path and I still get that Error.
I tried both python 3.6 and 3.7 aswell as a virtual environment and without a virtual environment. If I run it with PyCharm everything seems to work but from the terminal it doesn't.
It appears test/ is the root of your project structure. If you want
from lib.yolo.yolo_model import YoloModel
to work, then the directory containing lib/ must be in sys.path.
Try adding 'C:\\Users\\Name\\Desktop\\test' to sys.path.
Try to put the two files (module and main file) in the same directory. If the module name is helpermodule
on main write:
import helpermodule
#or import a specific class/method you might need

Import classes/functions from Python files saved in same folder showing "No Module Named" error

As per screen print, import shows error in Python 3.7 version, earlier it was working fine in version Python 2.7 and I am using IntelliJ Idea.
If you see, EOC related .py files are in the same folder and have classes which are being called in Main_EOC.py by passing objects which are inter-related. It's amazing to see the red line while importing files from same folder.
Please help me why it's showing such error
"This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.`"
Also, if you see the line which have full path, is not showing error
from EOC_Module.eoc.script.config import Config
Please help me if there is a way to add this full path on top of the code or other option.
The behavior of import path search changed between python2 and python3. The import path always includes the directory from which the main module was loaded, but it no longer includes directories from which modules were imported.
You need to change your import statement syntax as follows, if you want to import a module that lives in the same directory as the module in which you do the import:
# old way, import works if the named module is in this module's directory
import x
# new (Python3) way:
from . import x
For the second part: adding a path so all code can import from a certain directory: if that directory is (and will always be) relative to your main: you can add a few lines in the main module to make it available. Something like this:
import sys # if you haven't imported it already
import os.path
home = os.path.dirname(sys.argv[0])
sys.path.append( os.path.join(home, "EOC_Module/eoc/script") )
# now, you can import straight from the script directory
import EOC_Intraction
When using pycharm the root directory for your python executable is the same as the root directory of your project, this means that python will start looking for files in the root directory with this files:
.idea/
EOC_module/
logs/
reports/
sql/
This is the reason of why: from EOC_Module.eoc.script.config import Config works.
If you execute your code from the terminal with: python3 Main_EOC.py (not pycharm) the root directory for your python will be the same as the one containing the file, all the other imports will work but from EOC_Module.eoc.script.config import Config not.
So you need to make your imports from project directory if you are using pycharm.

Python "module not found" error when importing from folder?

I have the common problem of the "module not found" error when trying to import a file within a folder in my project directory as a package. I've tried several solutions from Stackoverflow answers, but none are working for me. Here's what's going on, and what I've tried:
I'm working in a conda environment devenv on a Flask project, using PyCharm, and have a project directory like this:
/some/path/project_root/
migrations/
static/
templates/
reporting/
__init__.py
code.py
tests.py
Inside the tests.py file there are import statements to import code.py as a module:
from .code import my_function
However, when I run (devenv) me#comp:project_root$ > python reporting/tests.py
I get the error: ModuleNotFoundError: No module named '__main__.code'; '__main__' is not a package
I tried appending the project directory path to $PYTHONPATH, and echo $PYTHONPATH returns /some/path/project_root/
What do I need to configure to get this to work properly? Also, whatever settings I need to change, can I make those settings specific to the development environment I'm using?
Change from .code import my_function to from code import my_function. The top level of a package is defined by the highest folder with an __init__.py file. So the top level of your project is the reporting folder and code.py does not need to be a relative import. Best to either avoid relative imports or get an editor like PyCharm that will take care of it for you!

Categories

Resources