DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Load Python Module through Relative Path


The relative path in sys.path only works for Python 3.x. The following importing method is path and OS agnostic. The only requirement is that the main script and the imported module files have a common parent folder.

$ take pkgex
$ Python -V
Python 3.6.3
mkdir -p {driver,step/impl}

$ cat << EOF > step/impl/inputstep.py
def myfunc(x, y):
  return x * 10 + y
EOF

$ cat << EOF > driver/main.py
import sys, os
sys.path.append(os.path.join(sys.path[0], '..'))
# or this: sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from step.impl.inputstep import myfunc
print(myfunc(3,5))
EOF

$ python driver/main.py
35

Note 1: for Python 3.x, the init.py file is unnecessary.

Note 2: sys.path.append('..') does not work.

import module, class and function

import module with full qualified name

import step.impl.inputstep
step.impl.inputstep.myfunc(3, 5)

import module

from step.impl import inputstep
inputstep.myfunc(3, 5)

import function

from step.impl.inputstep import myfunc
myfunc(3, 5)


Published

Dec 26, 2017

Last Updated

Dec 26, 2017

Category

Tech

Tags

  • module 4
  • path 2
  • python 136
  • relative 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor