import fails when running python as script, but not in iPython? -
i have project structured such:
folder1 | folder2 | tests
i have __init__.py in each folder. when in parent directory of folder1, run ipython , do
from folder1.folder2.tests.test1 import main main()
everything works fine. when run
python folder1/folder2/tests/test1.py
i importerror: no module named folder1.folder2.file1, import statement in test1
from folder1.folder2.file1 import class1
confused - guessing path issue don't understand wrong code (many similar setups in other folders) , why still works in ipython , not python run script.
the module search path (python 3 docu) different , without script file:
interactive python interpreter
(goes both python
, ipython
)
$ python python 2.7.3 (default, dec 18 2014, 19:10:20) [gcc 4.6.3] on linux2 type "help", "copyright", "credits" or "license" more information. >>> import sys >>> print(sys.path) ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/pil', '/usr/lib/pymodules/python2.7/gtk-2.0', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] >>>
note first entry being empty string. empty string relative path equivalent .
. relative paths in module search path relative current working dir of interpreter process, current working dir invoked interpreter. (which in case happened root of project.)
executing script file
$ echo 'import sys' > /tmp/pathtest.py $ echo 'print(sys.path)' >> /tmp/pathtest.py $ python /tmp/pathtest.py ['/tmp', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/pil', '/usr/lib/pymodules/python2.7/gtk-2.0', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']
note here, first entry absolute path of directory containing script file passed argument.