Before you mark this as a duplicate please read the whole problem, it is not the usual sys.path import error.
This is the directory structure of the module I'm trying to import
root
|_moduleDir1
| |_ myModule1.py
| |_ __init__.py
|_ moduleDir2
|_ myModule2.py
|_ __init__.py
I am working with 2 different machines. My script runs fine on one and I get the import error on the other. At first I thought it was just an environment issue, but I think something else is going on. When I run my script which imports myModule1.py with
import moduleDir1.myModule1
on the failing machine it throws the following import error.
ImportError: No module named myModule1
The reason I don't believe it is a PATH issue or a sys.path issue is that I have added the root directory to the appropriate environment variables and when I add
import moduleDir2.myModule2
above the myModule1 import in the script, it doesn't throw an import error so I know root is in sys.path or it would throw an error for them both. Also I don't think it is some issue with init.py because it works fine on the other machine. Both machines are running windows 10.
I'm stumped and I have searched and tested for hours with no luck. All I can find is posts that are issues with init.py or sys.path and those are not the right solutions for my problem. Any suggestions or thoughts on why else I might be getting an import error for one module and not the other when they are under the same parent directory would be appreciated.
One of reason may be the second machine that throws an import error does not have the read permission of directory.Please check the permission of the directory.
Related
There are 10+ SO posts about this already, none of the answers works for me and I still haven't seen an example of someone importing something from a sibling directory.
src
__init__.py
test.py
package1
__init__.py
module1.py
package2
__init__.py
module2.py
(_init_.py should not be necessary on python versions greater than 3.3 but I still have them there as they make no difference)
in test.py I have
import package1.module2
and it works fine however the problem is when I want to import something from package2 to package1, and vice versa. I have tried different import methods in module2.py and I receive these different error messages:
import src.package1.module1.py
with the error:
ModuleNotFoundError: No module named 'src'
and
from .. import package1
with the error:
ImportError: attempted relative import with no known parent package
The top answer here: How do I import a Python script from a sibling directory? also give me the exact error message as I showed above.
The answers here: How to import a Python module from a sibling folder? changes nothing.
Am I missing something or should it not be possible to import stuff between different folders/packages? Do I need the "sys.path hack"?
I gave almost all of the solutions given for similar questions a try, but none of them worked for me!
However, after banging my head to the wall, I found out that this solution does work by just removing one dot:
import sys
sys.path.append('..')
Just remove one dot from string within append method, i.e.:
sys.path.append('.')
or your can use:
sys.path.insert(0, '.')
Then you can import any module from a sibling folder.
I tried this using python 3.9.13 and it worked well.
I just spent several hours struggling with this same problem, trying various solutions from answers to the linked questions, and none of them worked. It was only when I cleared out the cruft from my various failed attempts and tried the stupidly simple solution from package1 import module1 (NB no dots, i.e. not a relative import) that it worked!
Note that your IDE may complain about this (PyCharm does in my current main project, but doesn't in a dummy project I created to test this solution separately). Nonetheless, when you run the code it should work (tested with Python 3.10 on Windows 11).
I'm trying to import a class in a different directory to another file, but can't seem to get it to work. I know this question has been asked a lot and I have looked through multiple stackoverflow solutions and at https://docs.python.org/3/tutorial/modules.html#packages
1: Importing files from different folder
2: import python file in another directory failed
I want to try to just use the method containing just __init__.py file instead of doing an import sys
My directory structure is as follows:
django_vue/
__init__.py
devices/
__init__.py
models.py
lib/
__init__.py
my_file.py
I'm trying to import the class Device from /django_vue/devices/models.py to /django_vue/lib/my_file.py by:
from devices.models import Device
However when I do that I still get the error:
from devices.models import Device
ModuleNotFoundError: No module named 'devices'
I'm not sure what I'm dong wrong since I already have the __init__ file in both directories. Any help is appreciated. Also I'm running python 3.6.
This is the folder structure I'm working with.
.
└── django_vue
├── devices
│ └── models.py
└── lib
└── file.py
When you run
$ python file.py
python has no way of knowing what's outside the directory.
python can't go back and then into devices/ just like that.
The easiest way to solve this would be to add the folder devices/ to sys.path. When python imports a module, it searches for the module from sys.path. Adding the path to devices/ would make it available for imports.
Here are my files.
# models.py
Device = 'device'
# file.py
import sys
sys.path.append('..') # adds the parent dir (which is django-vue/) to path
# django-vue dir has devices/ so now this is available for imports
# importing this works now
from devices.models import Device
print(Device)
Output
django_vue/lib$ python3 file.py
device
Think about it your are inside my_file.py and import something called devices.
How can python know where the name devices has come from.
It won't search your entire Drive for that module/package
Relative Import
use a relative import instead. write from ..devices.models import Device. This is telling python to go up one directory to the parent directory and that's where it will find the devices package. Your lib module should now work as a module
If you however run the my_file.py package directly (as in python C:/django_vue/lib/my_file.py)
You will still get an error. Not the same error; the new error will be something like
ImportError: attempted relative import with no known parent package
This is happening because you are actually running my_file.py
If you think about it why would you want to run my_file.py by itself when it is clearly a part of a package. Maybe you are just testing to see if the import works when you use your package. The problem with this is that it makes it seem like your packages relative imports don't work even though this actually works.
Create a main.py in django_vue and write from lib import my_file. This will run your my_file.py and you will notice there is no error.
What's happening here
Have you heard of __package__?
if you put print(str(__package__)) in your my_file.py and run my_file.py directly you will see that it prints None.
However if you run main.py (that you just created) you will see that when It reaches my_file.py, __package__ will actually be defined to something.
Ahhh... you see now it all makes sense; The error you originally got said something about no known parent package. If __package__ is undefined that means there is no relative parent package because the file was obviously run directly instead of as part of a package.
Consider Absolute imports
you also might want to consider using absolute imports because if you are working on the package you might change it directory structure while developing. so you need to keep changing the import references on the affected files.
Although you can find IDE's with python extensions that automatically to this as you change your directory. I believe VS Code does this automatically.
Replace the __init__ files with __main__.
I am having directory structure as
-Practice
-Connect
-connect.py -> having function abc
-__init__.py
-Pytest
-__init__.py
-file.py
file.1 contents
from ..connect.connect import abc
abc()
Getting error as
ValueError: attempted relative import beyond top-level package
I can use import from parent directory as
from connect.connect import abc
abc()
This is working. Need to know why relative import is not working
As people suggested i have added init.py in Practice directory and still getting same error
You need an __init__.py inside the top level Practice folder, so Python knows that it's supposed to be a package in its own right, as opposed to a random folder that happens to contain two packages.
You need an __init__.py in your Practice directory too. Otherwise, Pytest and Connect are separate toplevel packages and not sibling subpackages of the Practice package. Hence the error you're getting.
I know a lot of questions have been posted about the intra-package importing. I want to know whether the below is the way for Python 2.7 too.
Source/
anomalyCheck/
__init__.py
DLthput.py
ULPowerStats.py
ULThput.py
config/
__init__.py
configure.py
parserTools/
__init__.py
logParser.py
utilities/
__init__.py
plotLogResults.py
__init__.py
lteDebugger.py
---- lteDebugger.py----
import parserTools.logParser
import anomalyCheck.DLthput
import utilities.plotLogResults
import configuration.TDDFDDconfiguration
import anomalyCheck.ULthput
### Work done after here ####
------DLThput.py------
from ..utilities.plotLogResults import *
from ..parserTools.logParser import *
### Work done after here ####
------ULThput.py-------
from ..parserTools.logParser import *
from ..utilities.plotLogResults import *
Error :
Upon running the lteDebugger.py file, the error is
ValueError: Attempted relative import beyond toplevel package
File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\lteDebugger.py", line 2, in
import anomalyChecker.DLthput
File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\anomalyChecker\DLthput.py", line 1, in
I've read almost all available docs and Guido's guide for intra-package importing. Also, I guess I've everything exactly in the right place. Am I missing something here? Please point out. Thanks a lot in advance. :) :)
Edit 1: The Problem mentioned is solved by Amber's answer. So, lteDebugger.py is working fine by importing all other modules. Now, another problem is that, I am unable to solve is that... when I want to compile/interpret(whatever u want to call) the DLThput.py/ULthput.py , it is showing the same error as above ... ValueError: Attempted relative import beyond toplevel package. Do I have any solution other adding paths to sys hacks? I really don't want to do that unless it's the only thing to do.
So, how can I dodge this?
You're running lteDebugger.py, which means that any "packages" must be at least one level lower in the directory tree - they need to be contained inside a folder for Python to recognize them as packages rather than modules (and thus for relative imports to work).
anomalyCheck is recognized as a package, but its parent directory is not (because that's where lteDebugger.py is), and thus you aren't allowed to use relative imports to go up to that parent directory.
One way you could fix this is by moving everything except lteDebugger.py into a subdirectory, e.g.:
Source/
debugger/
anomalyCheck/
__init__.py
DLthput.py
ULPowerStats.py
ULThput.py
config/
__init__.py
configure.py
parserTools/
__init__.py
logParser.py
utilities/
__init__.py
plotLogResults.py
__init__.py
lteDebugger.py
and then lteDebugger.py would do things like import debugger.anomalyCheck.DLthput.py.
I'm trying to package my modules, but I can't seem to get it working.
My directory tree is something like the following:
snappy/
__init__.py
main/
__init__.py
main.py
config.py
...
...
and the code I'm using is
from snappy.main.config import *
I'm getting the error:
ImportError: No module named snappy.main.config
Any ideas what's going wrong? This is using Python 2.5 on Ubuntu 8.10.
Thanks in advance for your help.
It depends on where your script using the import resides and your system PYTHONPATH. Basically, to have that import working you should run your script (the one having the import) in the parent directory of snappy or your script should change sys.path to include it.
./alex
Is the parent directory of snappy in sys.path? If it's not, that's the only thing I can think of that would be causing your error.