annotate python/require.py @ 156:a9c3a32d8385

add a function for loading modules from the web
author Jeff Hammel <jhammel@mozilla.com>
date Wed, 27 Jul 2011 08:43:34 -0700
parents
children f145d7b1fbf7
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
156
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
1 def require(url):
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
2 """
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
3 import a module from the web
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
4 url should be like scheme://host.name/path/to/module.py
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
5 """
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
6 import os
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
7 import tempfile
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
8 import urllib2
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
9 contents = urllib2.urlopen(url).read()
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
10 filename = url.rsplit('/', 1)[-1]
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
11 module = filename.rsplit('.', 1)[-1]
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
12 dest = os.path.join(tempfile, filename)
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
13 f = file(dest, 'w')
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
14 f.write(contents)
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
15 f.close()
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
16 return imp.load_source(module, dest)
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
17
a9c3a32d8385 add a function for loading modules from the web
Jeff Hammel <jhammel@mozilla.com>
parents:
diff changeset
18 # TODO: make an equivalent method for a tarball