Using remote source code

pyapplico at gmail.com pyapplico at gmail.com
Sun Mar 25 01:39:47 EDT 2007


On Mar 25, 3:20 pm, a... at mac.com (Alex Martelli) wrote:
> <pyappl... 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 tohttp://www.aleax.it/foo.pya 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

Thanks for your help, now I can continue building my source code
generator. :)




More information about the Python-list mailing list