Importing remote modules

Hey Guys, Further to a conversation in IRC, I hope this little hack is useful for those of you who want to use JSON or make those monolithic dialogue scripts slightly more modular. :-) Abstract: I was looking for a way to run scripts that were also stored in the same place as the monolithic dialogue script. So I wrote something which can import python modules over the internet, it works in both jython and python. HOWEVER it is NOT standards compliant (need to adapt the zipimporter by Guido) and VERY VERY insecure. :) Background: Essentially I have whipped up an IDE that lets me design conversation flow. I can then publish a script to my server which runs it, but I didn't want the library logic to be included with the script at this point (liable to change and I don't want to be recompiling all the time). [IMG]http://i48.tinypic.com/n6vztu.png[/IMG] Code: The code below is a quick example that downloads and uses simple JSON parser and outputter I wrote (also very crap, non-standard but useful). def httpImport(sURL): """ @brief A quick and dirty non-standard module importer. @author John Hardy @note THIS IS VERY VERY VERY VERY INSECURE. USE AT YOUR OWN RISK. VERY INSECURE. @param sURL The url of the module to import. e.g. http://somedomain.com/foo.py @return A module object. e.g. ModuleType('foo') """ # Check we have a url. if not sURL: raise "Invalid URL '"+sURL+"'" # Get the python file name. sModuleName = sURL.split("/")[-1].split(".")[0] # Is it cached. import sys if sys.modules.has_key(sModuleName): return _dhttpImport[sModuleName] try: # Download the module and translate it into a source code string. import urllib2 sCode = "".join(urllib2.urlopen(sURL).readlines()) except: raise "No such module at path '"+sURL+"'." # Compile the module source. pCode = compile(sCode, sModuleName + '.py', 'exec') # Create the module object. import types pModule = sys.modules[sModuleName] = types.ModuleType(sModuleName) pModule.__loader__ = None pModule.__file__ = sURL pModule.__name__ = sModuleName exec pCode in pModule.__dict__ return pModule if __name__ == "__main__": json = httpImport("http://hosting.tropo.com/41199/www/modules/json.py") print json.inputJSON(json.outputJSON({"key" : ["value1", 2, "value3"]}))["key"][2] Hope it's useful! John


Please sign in to leave a comment.