V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
zmaplex
V2EX  ›  分享创造

Fetch-import,优雅的从网络中导入 Python 文件

  •  
  •   zmaplex · 2022-01-18 19:13:44 +08:00 · 1797 次点击
    这是一个创建于 800 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目

    https://github.com/zmaplex/fetch_import

    为什么要重新开一个帖子?

    无意重开,只是那个帖子写的太糟糕了,没有突出重点。

    介绍

    目前以及将来都是围绕从远程加载 Python 文件为核心开发,如果有问题欢迎提 issue.

    使用

    下面示例的远程资源包地址为:"https://cdn.jsdelivr.net/gh/zmaplex/fetch_import@main/example/sets.py"

    @im_fetch

    使用这个装饰器你可以很方便的像 import 一样从远程资源导入 Python 包资源。

    • 实现类似 import package 写法
    import sets
    sets.def_function()
    

    等价于:

    from fetch_import import im_fetch
    
    url = "https://cdn.jsdelivr.net/gh/zmaplex/fetch_import@main/example/sets.py"
    
    @im_fetch(url)
    def main():
        sets.def_function()
    
    
    • 实现类似 from package import * 写法
    from sets import *
    
    obj = ObjectClass()
    def_function()
    

    等价于:

    from fetch_import import im_fetch
    
    @im_fetch(url,["*"])
    def main():
        obj = ObjectClass()
        def_function()
    
    • 实现类似 from package import attr1,attr2 写法
    from sets import ObjectClass,def_function
    
    obj = ObjectClass()
    def_function()
    

    等价于:

    from fetch_import import im_fetch
    
    @im_fetch(url,["ObjectClass","def_function"])
    def main():
        obj = ObjectClass()
        def_function()
    
    7 条回复    2022-01-20 12:49:31 +08:00
    abersheeran
        1
    abersheeran  
       2022-01-18 19:42:44 +08:00
    实际上很多年前就有通过 import hook 进行 remote import 的东西了,不需要装饰器,用起来就跟本地有那个文件一样。https://python3-cookbook.readthedocs.io/zh_CN/latest/c10/p11_load_modules_from_remote_machine_by_hooks.html
    c0xt30a
        2
    c0xt30a  
       2022-01-19 02:57:55 +08:00
    纯好奇问下,如果要用 PyInstaller 打包成可执行文件,这个库还能正常工作么?我之前写的一些代码发现动态导入的库碰到 PyInstaller 打包很难掰扯
    warcraft1236
        3
    warcraft1236  
       2022-01-19 09:12:24 +08:00
    不知道是想解决什么问题,但是感觉这么做安全方面问题很大
    zmaplex
        4
    zmaplex  
    OP
       2022-01-19 20:03:44 +08:00
    @c0xt30a 没实际测试过,但是根据原理来讲大概率会出现问题。
    zmaplex
        5
    zmaplex  
    OP
       2022-01-19 20:04:12 +08:00
    @abersheeran 非常感谢,里面文档有些代码对我非常有启发!!!
    zmaplex
        6
    zmaplex  
    OP
       2022-01-19 20:04:46 +08:00
    @warcraft1236 安全问题......是个大问题
    abersheeran
        7
    abersheeran  
       2022-01-20 12:49:31 +08:00
    @zmaplex 嗯,有启发就好。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1767 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:35 · PVG 00:35 · LAX 09:35 · JFK 12:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.