Import in python -
this question has answer here:
- relative imports in python 3 4 answers
i read lot of answers related question asking, still not understand how make possible thing trying. let's go point. report simplified version of application.
suppose have main folder called project , inside src main package containing three subpackages:
- clustering (containing file: clustering.py)
- parser (containing file: parser.py)
- support_class (containing file: myclass.py)
in each folder, except project one, there __init__.py
now, python scripts contained in clustering , parser package should use both myclass.py contained in support_class.
i tried relative imports, not works because run scripts contained in clustering , parser package directly , not want use -m option.
es. python parser.py [arguments]
example of relative import used is:
from ..supportclass import myclass
i tried add package path sys.path not working because still tells me can't find module.
es.
sys.path.insert(0, "~/project/src") support_class import myclass.py
can suggest best way in python 2.7? if avoid sys.path option great because not solution much.
thanks in advance.
let's start project's folder architecture:
myproject/ └── src ├── clustering │ ├── __init__.py │ └── clustering.py ├── parser │ ├── __init__.py │ └── parser.py ├── support_class │ ├── __init__.py │ └── support.py └── main.py
if i'm not mistaken, issue want import support.py
within parser.py
, clustering.py
, being able run 2 independently if needed. 2 words you:
conditional imports
(and 1 more, after finding real other solution ;): pythonpath
)
with assumption scripts have if __name__ == "__main__":
section run tests, can have following imports:
clustering.py & parser.py:
if __name__ == "__main__": import sys import os package_parent = '..' script_dir = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(script_dir, package_parent))) support_class.support import support else: support_class.support import support
main.py:
from support_class.support import support
then, python clustering.py
, python parser.py heart's content!
which makes duplicate of https://stackoverflow.com/a/16985066/3425488
Comments
Post a Comment