【问题标题】:Exec Function, saving Methods/Classes/Variables -> Method执行函数,保存方法/类/变量 -> 方法
【发布时间】:2022-01-08 19:13:56
【问题描述】:

我正在编写一个用于创建更小的 Python 模块的库。我不确定我是否应该使用 compile() 而不是 exec(),它当前执行文件(执行全局范围内的任何基本代码)但没有存储为函数中的方法,以后可以通过不同的文件ETC...它将 python 文件加载为字符串

基本用法示例

from bagel import webImport

MyFile = WebImport("https://WhereFileIsLoaded.py")
# OR Feature Not Added Yet

MyModule = WebImport("https://WhereModuleIsLoaded.zip")

这是代码

import requests
from functools import wraps


# Thank you stack overflow
def withself(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper


def webImport( URL: str):
    data = requests.get(URL).text
    
    


    @withself
    def returnFunc(self):
        funcs = {}
        exec(data, {'__builtins__':__builtins__}, funcs)
        print("Executed Data")
        setattr(self, "funcs", funcs)
        return self
    
    # Function Object
    FUNC = returnFunc()

    for func in FUNC.funcs.items():
            # Can go through multipe because self.funcs 
            if not hasattr(FUNC.funcs, str(func[0])):
                print(func[0])
                # Setting the Atribute of this class -> The FUNCTION with the body of the functiion  
                setattr(FUNC, str(func[0]), FUNC.funcs[func])
                # exec(f"FUNC.{func}")

    return FUNC

这里是控制台输出,我正在使用 Python IDLE 来测试这个。

from webImport import webImport
web = webImport("https://pastebin.com/raw/xDJxwMri")

控制台输出

Console Screenshot

【问题讨论】:

    标签: python python-requests python-module python-exec


    【解决方案1】:

    而不是这一行,

    setattr(FUNC, str(func[0]), FUNC.funcs[func])
    

    使用这个

    setattr(FUNC, str(func[0]), FUNC.funcs.get(func[0]))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多