Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this correct way to import python scripts residing in arbitrary folders?

Tags:

python

This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directories, and I would like to be able to import them into new projects without having to jump through hoops.

This is the snippet:

def import_path(fullpath):
""" Import a file with full path specification. Allows one to
    import from anywhere, something __import__ does not do. 
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[-1]
return module

Its from here: How to do relative imports in Python?

I would like some feedback as to whether I can use it or not - and if there are any undesirable side effects that may not be obvious to a newbie.

I intend to use it something like this:

import_path(/home/pydev/path1/script1.py)

script1.func1()

etc

Is it 'safe' to use the function in the way I intend to?

like image 244
morpheous Avatar asked Jun 29 '10 03:06

morpheous


1 Answers

The "official" and fully safe approach is the imp module of the standard Python library.

Use imp.find_module to find the module on your precisely-specified list of acceptable directories -- it returns a 3-tuple (file, pathname, description) -- if unsuccessful, file is actually None (but it can also raise ImportError so you should use a try/except for that as well as checking if file is None:).

If the search is successful, call imp.load_module (in a try/finally to make sure you close the file!) with the above three arguments after the first one which must be the same name you passed to find_module -- it returns the module object (phew;-).

like image 176
Alex Martelli Avatar answered Nov 07 '22 23:11

Alex Martelli