Import python NOT module by path

I have a foo module containing util.py and bar.py.

I want to import it in an IDLE or python session. How should I do it?

I cannot find documentation on how to import modules not in the current directory or python default python. Having tried import "<full path>/foo/util.py" , and from "<full path>" import util

Closest I could get

 import imp imp.load_source('foo.util','C:/.../dir/dir2/foo') 

Which gave me permission on Windows 7.

+48
python import external python-module
Apr 15 '12 at 11:21
source share
4 answers

One way is to simply change your path :

 import sys sys.path.append('C:/full/path') from foo import util,bar 

Note that this requires foo to be a python package, i.e. contained the __init__.py file. If you do not want to change sys.path , you can also change the PYTHONPATH environment variable or install the module on your system . Remember that this means that other directories or .py files in this directory may be downloaded unintentionally.

Therefore, you can use imp.load_source . It needs a file name, not a directory (to a file that the current user can read):

 import imp util = imp.load_source('util', 'C:/full/path/foo/util.py') 
+65
Apr 15 '12 at 11:32
source share

You can configure the module search path using the PYTHONPATH environment variable or manually change the sys.path directory sys.path .

See the documentation for the Search> module at python.org.

+5
Apr 15 '12 at 11:26
source share

Try

 import sys sys.path.append('c:/.../dir/dir2') import foo 
+2
Apr 15 '12 at 11:29
source share

Following the phihag hint, I have this solution. Just specify the path to the source file load_src and it will load it. You must also provide a name so that you can import this module using this name. I prefer to do it like this because it is more explicit:

 def load_src(name, fpath): import os, imp return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath)) load_src("util", "../util.py") import util print util.method() 

Another (less explicit) way:

 util = load_src("util", "../util.py") # "import util" is implied here print util.method() # works, util was imported by the previous line 

Edit: This method has been rewritten to make it more understandable.

+1
Jan 01 '14 at 16:27
source share



All Articles