Import python module over the internet/multiple protocols or dynamically create module

后端 未结 4 1474
执笔经年
执笔经年 2021-01-02 06:55

Is it possible to import a Python module from over the internet using the http(s), ftp, smb or any other pro

4条回答
  •  我在风中等你
    2021-01-02 07:51

    In principle, yes, but all of the tools built-in which kinda support this go through the filesystem.

    To do this, you're going to have to load the source from wherever, compile it with compile, and exec it with the __dict__ of a new module. See below.

    I have left the actually grabbing text from the internet, and parsing uris etc as an exercise for the reader (for beginners: I suggest using requests)

    In pep 302 terms, this would be the implementation behind a loader.load_module function (the parameters are different). See that document for details on how to integrate this with the import statement.

    import imp
    modulesource = 'a=1;b=2' #load from internet or wherever
    def makemodule(modulesource,sourcestr='http://some/url/or/whatever',modname=None):
        #if loading from the internet, you'd probably want to parse the uri, 
        # and use the last part as the modulename. It'll come up in tracebacks
        # and the like.
        if not modname: modname = 'newmodulename'
        #must be exec mode
        # every module needs a source to be identified, can be any value
        # but if loading from the internet, you'd use the URI
        codeobj = compile(modulesource, sourcestr, 'exec')
        newmodule = imp.new_module(modname)
        exec(codeobj,newmodule.__dict__)
        return newmodule
    newmodule = makemodule(modulesource)
    print(newmodule.a)
    

    At this point newmodule is already a module object in scope, so you don't need to import it or anything.

    modulesource = '''
    a = 'foo'
    def myfun(astr):
        return a + astr
    '''
    newmod = makemodule(modulesource)
    print(newmod.myfun('bat'))
    

    Ideone here: http://ideone.com/dXGziO

    Tested with python 2, should work with python 3 (textually compatible print used;function-like exec syntax used).

提交回复
热议问题