Why does my namespace import not work when I use the os.chdir() to get to the package dir from script?
For example here is my package structure to demonstrate the problem.
testpk/
testpk/bin
testpk/bin/runit.py
testpk/lib
testpk/lib/libcode.py
testpk/lib/__init__.py
here is my lib code which just prints ive been imported
print "I've been imported"
contents of runit.py
#!/usr/bin/python
import sys, os
if __name__ == "__main__":
os.chdir('/home/moorepe/src/testpk')
print "working path = " , os.getcwd()
import lib.libcode
If i run runit i get this error:
moorepe@halifax$ bin/runit.py
Traceback (most recent call last):
File "bin/runit.py", line 6, in <module>
import lib.libcode
ImportError: No module named lib.libcode
However testing this with python command line it works as expected:
cd testpk
python -c "import lib.libcode
I've been imported
And this works from the bin dir:
cd testpk/bin
python -c "import os; os.chdir('/home/moorepe/src/testpk') ; import lib.libcode"
I've been imported
Can anyone explain what is going wrong?
So the reason this didnt work is that python uses the current dir as a path in addition to the PYTHONPATH.
so this code works by adding sys.path.append(“.”) because im forcing a current working dir as a path addition.
If you add a
'.'for the current directory to thesys.pathsearch folder list, then theos.chdir()will become effective and theimport lib.libcodeshould start working:File
runit.py: