I have a module foo, containing util.py and bar.py.
I want to import it in IDLE or python session. How do I go about this?
I could find no documentation on how to import modules not in the current directory or the default python PATH.
After trying import "<full path>/foo/util.py"
,
and from "<full path>" import util
The closest I could get was
import imp
imp.load_source('foo.util','C:/.../dir/dir2/foo')
Which gave me Permission denied on windows 7.
Give this a try
One way is to simply amend your path:
Note that this requires foo to be a python package, i.e. contain a
__init__.py
file. If you don't want to modifysys.path
, you can also modify thePYTHONPATH
environment variable or install the module on your system. Beware that this means that other directories or.py
files in that directory may be loaded inadvertently.Therefore, you may want to use
imp.load_source
instead. It needs the filename, not a directory (to a file which the current user is allowed to read):Following phihag's tip, I have this solution. Just give the path of a source file to
load_src
and it will load it. You must also provide a name, so you can import this module using this name. I prefer to do it this way because it's more explicit:Another (less explicit) way is this:
Edit: the method is rewritten to make it clearer.
You could customize the module search path using the
PYTHONPATH
environment variable, or manually modify thesys.path
directory list.See Module Search Path documentation on python.org.