Continue execution with TLD
In general, try keeping runtime at the top level. This will greatly simplify your import.
If you need to do a lot of import addressing with relative import, perhaps the best way.
Path change
Other posters mentioned PYTHONPATH . This is a great way to do this forever in your shell.
If you do not want / cannot control the PYTHONPATH project trace directly, you can use sys.path to get yourself out of the adrenaline rush.
Using sys.path.append
sys.path is just a list inside. You can add to it to add material to your path.
Let's say that I'm in /bin and there is a markdown library in lib/ . You can add relative paths with sys.path to import what you want.
import sys sys.path.append('../lib') import markdown print markdown.markdown(""" Hello world! ------------ """)
A word to the wise: Not too crazy with sys.path add-ons. Keep your circuit simple to avoid too much confusion.
Too impatient imports can sometimes lead to cases where the python module must import itself, after which execution will stop!
Using packages and __init__.py
Another important trick is to create python packages by adding __init__.py files. __init__.py loads before any other modules in the directory, so this is a great way to add imports across the entire directory. This makes it an ideal place to add the sys.path hacker.
You do not even need to add anything to the file. Just make touch __init__.py on the console to make the directory a package.
See this SO post for more details .
mvanveen
source share