Monday, December 2, 2013

python import from another dir (another package, no the current)


Usually an import from another source under the same package is straight.
All you have to do is to declare import for the source, but if the source is outside, another directory, you have two alternatives: use sys.path or PYTHONPATH envvar.

To use PYTHONPATH envvar you just append to it the new path that contains the source to be used by the import statement.


Using sys.path

Supposing the scenario below, follow by the example.



 
- The D:\work\devcli\python\Sandbox\examples\modules\testB\modTest3.py file, contains:

def printTest3():
    print('test3')

   
- The D:\work\devcli\python\Sandbox\examples\modules\testA\modTest2.py, contains:
def printTest2():
    print('test2')

   
- The D:\work\devcli\python\Sandbox\examples\modules\testA\modTest1.py, contains:
def printTest1():
    print('test1')
   
import sys, modTest2 
# using absolute path
#sys.path.append('D:/work/devcli/python/Sandbox/examples/modules/testB')
# or using relative path
sys.path.append('../testB')
import modTest3

def printTest1():
    print('test1')

printTest1()
modTest2.printTest2()
modTest3.printTest3()



- Running, the example you get:

test1
test2
test3


 |

No comments:

Post a Comment

eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...