view talosnames/require.py @ 42:cc0edf61ab21

require all the things!
author Jeff Hammel <jhammel@mozilla.com>
date Sun, 12 Aug 2012 23:10:16 -0700
parents 1b18b2746e69
children
line wrap: on
line source

import imp
import os
import sys
import tempfile
import urllib2

def require(*urls, **filenames):
    """
    import a module from the web
    url should be like scheme://host.name/path/to/module.py
    """

    tempdir = tempfile.mkdtemp()
    sys.path.insert(0, tempdir)
    retval = []

    for url in urls:
        contents = urllib2.urlopen(url).read()
        filename = filenames.get(url, None)
        if not filename:
            filename = url.rsplit('/', 1)[-1]
        module = filename.rsplit('.', 1)[0]
        dest = os.path.join(tempdir, filename)
        f = file(dest, 'w')
        f.write(contents)
        f.close()
        try:
            _module = imp.load_source(module, dest)
        except Exception, e:
            raise
#            import pdb; pdb.set_trace()
        retval.append(_module)

    sys.path.pop(0)
    return retval

# TODO: make an equivalent method for a tarball