Import python package from local directory into interpreter
Import python package from local directory into interpreter
You can use relative imports only from in a module that was in turn imported as part of a package — your script or interactive interpreter wasnt, so of course from . import
(which means import from the same package I got imported from) doesnt work. import mypackage
will be fine once you ensure the parent directory of mypackage
is in sys.path
(how you managed to get your current directory away from sys.path
I dont know — do you have something strange in site.py, or…?)
To get your current directory back into sys.path
there is in fact no better way than putting it there.
See the documentation for sys.path:
http://docs.python.org/library/sys.html#sys.path
To quote:
If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.
So, theres no need to monkey with sys.path if youre starting the python interpreter from the directory containing your module.
Also, to import your package, just do:
import mypackage
Since the directory containing the package is already in sys.path, it should work fine.
Import python package from local directory into interpreter
Keep it simple:
try:
from . import mymodule # myapp case
except:
import mymodule # __main__ case