python "No module named" error when calling a submodule -


i'm having trouble import statement python reports there no module named the_page or the_generator.

task_a.py contains import generator.the_page thepage, , when run main script, causes no problem.

the_generator.py contains import tasks.task_a, when run main script, python throws following error..

traceback (most recent call last):   file "/generator/the_generator.py", line 7, in <module>     import tasks.tasks_a   file "/generator/tasks/tasks_a.py", line 3, in <module>     import generator.the_page thepage importerror: no module named the_page 

here's structure.

generator/     __init__.py     the_generator.py     the_page.py     tasks/         __init__.py         task_a.py 

maybe can problem guys. help!

running scripts middle of package bad idea, number of reasons, obvious of 1 you're running into: when import generator.the_generator somewhere, generator ends package, absolute import of generator.the_page, or relative import, work fine. when run script generator/the_generator.py, there no generator.the_generator, __main__, , there no generator package. other way python know how find generator.the_page if parent directory of generator on sys.path, isn't.

as can guess, can work around munging sys.path put appropriate parent directory on there… bad idea too.

there many other problems solution. seriously, can lead same module being imported twice (because python has no way of knowing 2 apparently-unrelated names happen refer same module). it's hard deploy (you can't install script /usr/local/bin if depends on being inside package…), won't work if package run out of .zip or .egg, etc.


there 2 standard ways solve this.

first, run script module rather script. parent directory of generator, python -m generator.the_generator instead of python generator/the_generator.py.

a major advantage of works in normal installed deployments, when generator in site-packages somewhere, in testing.

alternatively, create script sits alongside generator, , run that, not module inside of it. can trivial moving if __name__ == '__main__': code in the_generator.py function, writing two-line wrapper:

import generator.the_generator generator.the_generator.main() 

again, works in normal installed deployments. plus, means script can installed bin directory, making things easier, pip or ipython.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -