Using remote source code
Alex Martelli
aleax at mac.com
Sun Mar 25 01:20:45 EDT 2007
<pyapplico at gmail.com> wrote:
> Is there any possible way that I can place a .py file on the internet,
> and use that source code in an .py file on my computer?
You can write an import hook in any way you like; see
<http://www.python.org/dev/peps/pep-0302/> .
Here's a trivial example (bereft of much error checking, etc). I've
uploaded to http://www.aleax.it/foo.py a toy module w/contents:
def foo(): return 'foo'
Here's a tiny program to import said module from my site:
import urllib2, sys, new
theurl = 'http://www.aleax.it/'
class Examp(object):
names = set([ 'foo', ])
def find_module(self, fullname, path=None):
if fullname not in self.names: return None
self.foo = urllib2.urlopen(theurl+fullname+'.py')
return self
def load_module(self, fullname):
module = sys.modules.setdefault(fullname,
new.module(fullname))
module.__file__ = fullname
module.__loader__ = self
exec self.foo.read() in module.__dict__
return module
def hooker(pathitem):
print 'hooker %r' % pathitem
if pathitem.startswith(theurl): return Examp()
raise ImportError
sys.path_hooks.append(hooker)
sys.path.append(theurl)
import foo
print foo.foo()
Alex
More information about the Python-list
mailing list