How to make/manage Python Paths and Packages/Modules

Give a requirement that there is a structure like below:
                - test.py
                      |---- hi
                             |---- hello.py

How "test.py" calls a function in "hello.py"?

These works for both Python2 and Python3 

* Using sys.path: using "print(sys.path)" to see what is inside.
"hello.py"
     def hi():
          print('hi')
"test.py"
     import sys
     sys.path.append('./hi')
     import hello
     hello.hi()


* Using PYTHONPATH 
export PYTHONPATH=$PYTHONPATH:`pwd`/hi
"test.py"
     import hello
     hello.hi()


* Turn it Python Package
Create an empty file "__init__.py" in "hi"
=> This makes "hi" a package.
"test.py"
     from hi import hello
     hello.hi()


* If only using Python3
"test.py"
     from hi import hello
     hello.hi()


* Notes
Where the module is in your filesystem:
>>> import tensorflow as tf
>>> tf.__file__
'/home/tuan/.local/lib/python2.7/site-packages/tensorflow/__init__.pyc'

or using imp
>>> import imp
>>> imp.find_module('tensorflow')
(None, '/home/tuan/.local/lib/python2.7/site-packages/tensorflow', ('', '', 5))

Python manipulate the sys.path using "site"
>>> import site
>>> site.__file__
'/usr/lib/python2.7/site.pyc'



Post a Comment

0 Comments