ModuleNotFoundError in python (spyder project) - python

1. The environment
I am working in Windows 10 with Anaconda/Spyder tools.
I have a python project organized as follow.
folder_project
test_all.py
folder_utils
__init__.py
function1.py
folder_tests
__init__.py
test_function1.py
The init.py files are empty files.
Basic idea for implementing code coverage of my code (maybe methodology can be improved) is that I will have:
one python file to test in different manners one function
test_function1.py will contain one function per test:
def test_001():
...
test_all.py file will call all functions for all test_functionXXX.py files
In Spyder, I have taken care to add in PYTHONPATH the folder_project.
2. The problem
I encounter error in importing the folder_tests package...
I have in test_all.py
import folder_tests.test_function1
def main():
# Testing function1
test_function1.test001()
And I get following error:
ModuleNotFoundError: No module named 'folder_tests.test_function1'
If I only do
import folder_tests
I have no error message, but then I can do nothing with that...
If I change the import statement in
from folder_tests import test_function1
I get following error:
ImportError: cannot import name 'test_function1' from 'folder_tests'
Please, any idea how I could correct that?
I thank you in advance for your help!
Bests,
Pierrot

The origin of the error doesn't seem related to python, but spyder.
I stopped and re-launched spyder, it didn't work, I simplified name of files, and it worked, and I then re-used the previous file names, and it still works...
Kind of a headache here...
Sorry for the bother.
Bests,
Pierrot

Pierrot, regarding your answer I agree, it is a total headache but I got to the bottom of the issue for 2 scenarios:
If the folders which you referenced are not housed in a folder that is recognized by Spyder as a project folder then this issue occurs. In your case this would be folder_project. This can be tested by going to Projects->Open Project if the folder you select is not recognized as a project folder it will tell you, and not open it. Can be fixed by Project->New Project->Existing Directory
Folder name the same as file name (Spyder specific, not an issue using other IDEs such as pycharm)
I had the folder name the same as the file name e.g. folder called 'email' and file inside called 'email.py'. When I tried to import, it raised 'ModuleNotFoundError: No module named 'email'.
Here's the version that failed with matching file and folder name:
import email.email as e
Here's the version that worked with differentiated file (added and 's') and folder name:
import emails.email as e

Related

VSCode Python error in importing modules from subdirectories

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

Python - cannot import name

I think just the code will be enough for you to understand everything
exampleforstack.py
from psgss import login,password
print(login,password)
psgss.py
login = "login"
password = 33
and here is the error
Traceback (most recent call last):
File "b:\vse parsers\exampleforstack.py", line 4, in <module>
from psgss import login,password
ImportError: cannot import name 'login' from 'psgss' (b:\vse parsers\psgss.py)
idk what to do, this error appears every time i try to import any files.
Modules are imported without errors, problems appear only with files,
thanks in advance
I see a couple potential problems, depending on your setting of PYTHONPATH, what other files are present, and details of your invocation:
Imports should ideally either be in a directory listed on PYTHONPATH, if they're outside the current package. This probably isn't directly relevant to you though, since you're likely thinking of psgss.py and exampleforstack.py as parts of the same package.
If you're not importing from something outside the current package, i.e. something on the PYTHONPATH, it should be in a directory with an __init__.py. (IIRC, __init__.py is no longer strictly required, but you still see it a lot, so try adding it if you don't have it.) Adding __init__.py is unlikely to be enough by itself, though. It effectively says psgss.py and exampleforstack.py are part of the same package, but that's not what you're conveying in your imports as written.
Try changing the import line to from .psgss import login, password. The period before "psgss" is critical, since it tells Python to look for the file / module in the same directory as the invoking code. (This is a difference in "relative imports" versus "absolute imports", and changed in Python 2 -> Python 3. Python 2 tried to be much more forgiving of such omissions, but would occasionally import from the PYTHONPATH when an import from the local directory was intended. Python 3 is more strict, to avoid importing global packages when local ones are intended - or vice versa.)
However, you're likely still not done, depending on where you are on the command-line when doing the import. Python expects you to be outside that "local package" at invocation, so the expected file structure is something like this:
package_support/
+------entrypoint.py
+------package/
+-------__init__.py
+-------exampleforstack.py
+-------psgss.py
In exampleforstack.py you would have from .psgss import login, password, but you would run the code from the package_support/ directory, and entrypoint.py would have a line like import package.exampleforstack which would load exampleforstack.py, which would load psgss.py. Other things that go in package_support/ would be a README, non-Python scripts, and possibly code / directories specifically for packaging & deploying the package/ contents.

VS Code Python import path when starting in a subfolder does not behave the same in VS Code and at run time

I have a sample Python application that I'm playing around with in VS Code. The folder structure that I have is that the application is in a sub-folder. The readme.md and code-workspace files and the like are in the root of the project, and then I have a sub-folder for my application code.
I have a file that represents the entry point of the application, and other files containing supporting logic in the same folder. When I try to import from those files VS Code wants me to put a period before the module (file) name.
from .my_code_file import my_class
But that errors when I run the application. It runs just fine if I remove the leading period.
from my_code_file import my_class
Why does VS Code Intelisense think I need a period in front of the module name?
This is a representation of the file and folder structure:
|-AppCode
| |-my_code_file.py
| |-application_entry_point.py
|
|-readme.md
|-MyProject.code-workspace
The reason is that when importing other files, the standard import statement should be: "from AppCode.my_code_file import my_class", and VScode starts from the parent folder of the currently opened file by default. Obviously, VSCode cannot find the folder "AppCode" from the folder "AppCode", we can use the following two methods to help VSCode find "my_code_file":
Please add the following statement, which adds the path of the file to be imported to the system path, and VSCode can find her in the system path:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
If Pylint reports an error "Unable to import'AppCode.my_code_file", but the code can run, we can use
"python.linting.pylintArgs": [
"--disabled=E0602"
]
to turn off this warning.
2.We can also use "from my_code_file import my_class", the code can be executed to get the result.
If Python reports an error "unresolved import'my_code_file", but the code can run, we can use
"python.analysis.disabled": [
"unresolved-import",
],
to close this warning.
Reference: readable-pylint-messages.
I was running into issues just like this recently and after some googling I found several ppl recommending I download microsoft's new Python extension called Pylance.
I've been using it for about a week and it solved all of my issues I was having that involved my application being confused w/ file structure. I'd recommend giving it a try!
https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance
Cheers,
-Andrew

Importing from sibling directory

I have searched this question over stackoverflow but can't find an answer that fixes this. I am trying to learn how to do proper imports with python.
I am using Python 3.8.2 and I have the following simple directory setup.
main_folder\
folder1\
myclass.py
folder2\
testclass2.py
testclass1.py
Both testclass1.py and testclass2.py have this inside:
from folder1.myclass import Myclass
This works fine for testclass1.py, but when I run in testclass2.py it gives me an error.
ModuleNotFoundError: No module named 'folder1'
Even though I had read Python no longer requires this, I inserted an __init__.py file into folder1. This generated the same error. I then tried following directions for the init file in this article but there was no improvement. I also tried using relative paths versus absolute paths for import, but no success.
Help is much appreciated.
From testclass2.py the import should be like this:
from ..folder1.myclass import Myclass

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.

Categories

Resources