This question already has answers here:
Import a module from a relative path
(22 answers)
Closed 7 years ago.
I have a folder structure like this
main_folder
|
|--done
| |
| |--test1
| |--__init__.py
|
|---check.py
__init__.py:
class Tries(object):
def __init__(self):
print "Test"
check.py:
from done.test1 import Tries
Tries()
Error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-8-10953298e1df> in <module>()
----> 1 from done.test1 import Tries
ImportError: No module named done.test1
I am not able to import modules from the nested folder. Is there any way to do this.
Edit:
After Salva's answer I changed my structure like this
.
├── check.py
|--__init__.py(no content)
└── done
├── __init__.py(no content)
└── test1
└── __init__.py <-- this files contains your Tries class
Same error is thrown now also.
You need a file __init__.py in each directory you want it to be considered a package so you need it in both directories:
.
├── check.py
└── done
├── __init__.py
└── test1
└── __init__.py <-- this files contains your Tries class
In the following file/folder structure your code just works here:
.
├── check.py
└── done
└── test1.py
When I run check.py it prints Test. I didn't use __init__.py though. What you described as __init__.py I made test1.py.
Try to import package done first
import done
If it doesn't work, probably you are running script from different folder than you specified (in this case main_folder)
From logs it seems like you are using IPython, in this case try to add your folder as module path
import sys
sys.path.append('path/to/your/main_folder')
import done
Related
I have this file structure
.
└── sample
├── one
│ ├── __init__.py
│ └── util.py
└── two
├── __init__.py
└── test.py
Here is the content of util.py
def isOk():
return True
Here is the content of test.py
from sample.one import util
Whenever I'm inside the [two] folder and I type
python test.py
I get
Traceback (most recent call last):
File "test.py", line 1, in <module>
from sample.one import util
ModuleNotFoundError: No module named 'sample'
How is that possible when I create all folders and __init__.py by the book?
It seems that a method to invoke it might be
python -m two.test
If one and two are both subpackages of sample, then you should add a sample/__init__.py which may be empty.
If you then invoke python -m sample.two.test from the right directory, it should work.
You could even add package-relative imports like this:
# test.py
from ..one import util
Please add the dir path to your PYTHONPATH
export PYTHONPATH=/PATH/TO/DIR/WHICH/CONTAINS/SAMPLE
2 real nice links to go through are:
https://docs.python.org/3/tutorial/modules.html
https://docs.python.org/3/reference/import.html
I have the following folder structure:
PROJECT_DIR
| --helpers
| |--utils.py
| --stuff
| |--script.py
I need to run script.py as a script, and from it, I need to use a function from helpers/utils.py.
I tried relative importing from ..helpers.utils import func, but it says
ImportError: attempted relative import with no known parent package
so I added an empty init.py file to each folder, including PROJECT_DIR.
Then I read that while running as a script, the python compiler runs the script as if it was the main module, so it doesn't see any other modules outside so relative import cannot be used.
But what should I do if I need to use that function? It's a fairly simple use case, I can't get my head around why it's so hard to import a function from a file outside the current directory. Tho I'm not really interested in the whys, I'd just like to know a solution how people do this.
root_project
└── proj
├── __init__.py
├── helpers
│ ├── __init__.py
│ └── utils.py
└── stuff
├── __init__.py
└── script.py
With this structure just cd to root_project and use this command:
python -m proj.stuff.script
I try to understand how to split up python files belonging to the same project in different directories. If I understood it right I need to use packages as described here in the documentation.
So my structure looks like this:
.
├── A
│ ├── fileA.py
│ └── __init__.py
├── B
│ ├── fileB.py
│ └── __init__.py
└── __init__.py
with empty __init__.py files and
$ cat A/fileA.py
def funA():
print("hello from A")
$ cat B/fileB.py
from A.fileA import funA
if __name__ == "__main__":
funA()
Now I expect that when I execute B/fileB.py I get "Hello from A", but instead I get the following error:
ModuleNotFoundError: No module named 'A'
What am I doing wrong?
Your problem is the same as: Relative imports for the billionth time
TL;DR: you can't do relative imports from the file you execute since
main module is not a part of a package.
As main:
python B/fileB.py
Output:
Traceback (most recent call last):
File "p2/m2.py", line 1, in <module>
from p1.m1 import funA
ImportError: No module named p1.m1
As a module (not main):
python -m B.fileB
Output:
hello from A
One way to solve this is to add module A into the path of fileB.py by adding
import sys
sys.path.insert(0, 'absolute/path/to/A/')
to the top of fileB.py.
I'm trying to build a Python program with the "structure" shown at the end.
The problem is that actions should be able to be executed as scripts as well (I've already included a main in them). When I try to execute DummyAction.py imports keep complaining they can't find misc.
How can I use DummyAction.py as a script and still use the functions in utils.py?
DummyAction.py contains a class called DummyActionClass, and the same for DummyTrigger.py. In utils.py there are several functions that both actions and triggers use and MMD.py contains the main.
/MMD
├── __init__.py
├── MMD.py
├── /actions
│ ├── __init__.py
│ ├── DummyAction.py
├── /misc
│ ├── __init__.py
│ ├── utils.py
└── /triggers
├── DummyTrigger.py
└── __init__.py
The import in DummyAction.py and DummyTrigger.py is:
from misc import utils
And the error is:
File "DDM/actions/DummyAction.py", line 11, in <module>
from misc import utils
ImportError: No module named misc
Seen the updated question, I think the problem is that you should do the import including the root of your dependecies tree: MMD.
So they should all look like:
from MMD.misc import utils
And also you need to call python with the -m option:
python -m MMD.actions.DummyAction
Edit: You said that MMD.py contains the main but it can't be your executable, and that's because is a module (is inside a directory with an __init__.py file). MMD is like your library so you need the executable to be outside and use such library.
You can find [here] some guidelines on how to organize your project.
If you can change you project structure I'll suggest to do it like this:
MMD/
├── runner.py
└── mmd
├── __init__.py
├── main.py
├── /actions
│ ├── __init__.py
│ ├── DummyAction.py
├── /misc
│ ├── __init__.py
│ ├── utils.py
└── /triggers
├── DummyTrigger.py
└── __init__.py
Then in any file inside the mmd directory every import should start with mmd, for example:
from mmd.misc import utils
from mmd.actions import DummyActions
And you put your main code that now is inside MMD.py inside a Main class in main.py, with something like:
# main.py
from mmd.misc import utils
class Main:
def start_session(self):
utils.function()
# etc ...
And then in runner.py you do something like:
# runner.py
from mmd.main import Main
cli = Main()
cli.start_session()
This way inside the MMD directory calling python runner.py you would execute your code, and you can also make executable runner.py so a simply ./runner.py will run your code.
And run your module with:
python -m mmd.actions.DummyAction
I'd do it like this, becasue this way is open to future implementation (and is almost like in the line guides).
If instead you can't, then you can give it a try at removing __init__.py from the MMD directory.
I assume this is a directory structure you're talking about, in which case python doesn't know where to look for utils.py - it tries the local directory, a few places in the path then gives up. It's simple enough to modify the path:
import sys
sys.path.append("/MMD/misc")
import utils
and you should be away.
I've found a "workarround"
try:
#When executing from the main
from misc import utils
except:
#When executing as a standalone script
from MMD.misc import utils
that allows to:
Call the module as a script (while using other modules): python -m MMD.actions.DummyAction
Call the main program and use the module: python MMD/MMD.py
Although I'm not sure if it's strictly correct to use a try - except block with an import, so feel free to add comments or other solutions.
The complete solution would be:
MMD.main
from misc import utils
from actions import DummyAction
class MMD():
def __init__(self):
a = DummyAction.DummyActionClass()
utils.foo()
if __name__ == '__main__':
d = MMD()
Then in actions/DummyAction.py:
try:
#When executing from the main
from misc import utils
except:
#When executing as a standalone script
from MMD.misc import utils
class DummyActionClass():
def __init__(self):
utils.foo()
if __name__ == '__main__':
a = DummyActionClass()
And finally in misc/utils.py:
def foo():
print "Foo was called"
This question already has an answer here:
Is "from ... import ..." sometimes required and plain "import ..." not always working? Why?
(1 answer)
Closed 2 years ago.
I have the following structure:
project
├── sum_package
│ └── sum_module.py
├── testing.py
I try to access sum_module.py from testing.py in two different ways:
First:
from sum_package import sum_module
sum_module.great_summation(1,2)
Second:
import sum_package
sum_package.sum_module.great_summation(1,2)
First works, second doesn't:
AttributeError: module 'sum_package' has no attribute 'sum_module'
Can someone explain why?
EDIT: tried adding __init__.py into either/both the package folder / the project folder, does not help.
EDIT 2: so it seems like the problem is $PYTHONPATH. I've tried adding my src (project) directory as PYTHONPATH, like this:
export PYTHONPATH = "$PWD"
while in src, but I still get the same error. What else am I missing?:)
project
├── __init__.py
|
├── sum_package
├── __init__.py
|
│ └── sum_module.py
├── testing.py
The __init__.py files are required to make python treat directories containing the file as packages. Make your folder structure like this. In the simplest case, __init__.py can just be an empty file.
Then try
testing.py
from sum_package import sum_module
sum_module.great_summation(1,2)