Skip to main content
 首页 » 编程设计

python之如何加载用户代码

2025年05月04日8cmt

我有一个程序可以根据用户提供的 JSON 代码自动生成数据结构。我还想提供一个选项,允许用户编写自己的函数以编程方式生成此数据结构。有没有办法让 Python 通过路径加载任意模块并返回该模块的命名空间,以便我可以从我的程序中调用用户的函数?

例如,我想要如下内容:

def make(custom): 
    if not custom: 
        return helper('example.json') 
    else: 
        return load('path/to/user-script.py').make()  # this line here 

请您参考如下方法:

您可以使用 imp.load_source 导入命名的 .py 文件,就好像它是一个模块一样;见this question .

这通常是一件非常奇怪的事情,但加载不在 Python 模块层次结构中的用户 Hook 似乎是一个不错的借口。 :)


This Python bug声称 load_source 在 Python 3 中已过时,并建议使用更麻烦且不太明显的调用:

importlib.SourceFileLoader(name, path).load_module(name)