Reputation: 403
I am trying to implement following hierarchy. My final goal is myscpt.sh should run from any folder
But I am getting import errors.
What is the best approach to implement such type of hierarchical architecture?
FooSoft
|
|-- foo/
|
|-- test.py
|
|-- common/
|
|-- utils/
|
|-- api/
|
|-- scripts/
|-- myscript.py
|
|-- bin/myscpt.sh
|
|-- etc/foo.conf
bin/myscpt.sh
/usr/bin/python /path/FooSoft/foo/script/myscript.py /path/FooSoft/etc/foo.conf
foo/script/myscript.py
from ..common import *
from ..utils import *
from ..test import *
.
.
<Doing some stuff>
I am using .. import
in most of modules to avoid absolute path.
Upvotes: 0
Views: 224
Reputation: 15548
Explicit relative imports with leading dots like from ..common import anything
can be used only from a code that has been imported as a submodule of the package e.g. foo.scripts
, but not from the the code imported as __main__
script, even if the script path contains .../foo/scripts/...
. The main script must use absolute imports or it can be used as module by something like python -c "from foo.scripts import myscript; myscript.run()"
. (install the foo or use PYTHONPATH=/path/FooSoft). See Intra-package References in the docs or a similar question.
Upvotes: 0
Reputation: 2753
Typically I resolve import errors by always using the package root as a reference.
First, I would include a setup.py file in the project root, and add in a minimal setuptools wrapper.
python setup.py develop
Then you don't have to worry about where you run the script from. Your imports become as follows:
from foo.common import *
from foo.utils import *
from foo.test import *
Upvotes: 1