Reputation: 1
I have a simple situation on a linux system:
ls test_repo
example __init__.py text
In text
directory, I just have 2 files:
__init__.py ex.py
In example
directory, I have just 2 files again:
__init__.py test.py
In ex.py
I have the code:
def test():
print(10)
Now, in text directory I want to import it:
from text.ex import test
print(test())
But when I run the file in the example directory as well as out of it: python test.py
I get the error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from text.ex import test
ModuleNotFoundError: No module named 'text'
How can I import the function?
Should I put something in __init__.py
?
Upvotes: 0
Views: 78
Reputation: 61
In your case, you might add this into the very beginning line of your test.py
import sys
sys.path.insert(0, "..")
Because your test.py
is located inside example
directory not the root
directory.
Upvotes: 0
Reputation: 4130
For everyone having this import issue,let me explain how this work
first when you import certain module to a file,how does it know where to find the module?
when we import module,python check for that module in multiple locations.those locations are in sys.path
.
If you print sys.path
it will give a list of locations where python checks when we run an import
statement.
in my machine output looks like this
so what are the values in this list
so python check all these location when you run an import.
when you run python test.py
inside the example directory,this is what happens
sys.path
list (which is test_repo/example
)test.py
file has import statement from text.ex
modulesys.path
list to load text.ex
moduleex.py
file is inside the test_repo/text
module and sys.path
doesn't have the location for the test_repo/text
it will gives the error No module named 'text'Upvotes: 0
Reputation:
Look at this question, on StackOverflow. It has multiple examples for importing files, so just use the one that best fits in your situation.
Upvotes: 1