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

后端 未结 4 1439
执笔经年
执笔经年 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:33

    Another version,

    I like this answer. when applied it, i simplified it a bit - similar to the look and feel of javascript includes over HTTP.

    This is the result:

    import os
    import imp
    import requests
    
    def import_cdn(uri, name=None):
        if not name:
            name = os.path.basename(uri).lower().rstrip('.py')
    
        r = requests.get(uri)
        r.raise_for_status()
    
        codeobj = compile(r.content, uri, 'exec')
        module = imp.new_module(name)
        exec (codeobj, module.__dict__)
        return module
    

    Usage:

    redisdl = import_cdn("https://raw.githubusercontent.com/p/redis-dump-load/master/redisdl.py")
    
    # Regular usage of the dynamic included library
    json_text = redisdl.dumps(host='127.0.0.1')
    
    • Tip - place the import_cdn function in a common library, this way you could re-use this small function
    • Bear in mind It will fail when no connectivity to that file over http

提交回复
热议问题