python - 如何在没有导入库的情况下获取python文件中的函数定义?

标签 python python-3.x

我有一个包含内容的文件 test.py 。文件结构定义如下。我无法控制文件的结构。

import *some python libraries*

def my_function:
    content = "This is my function"
    return content

我想编写一段代码来读取这个 python 文件并返回函数 my_function 的返回值,即“这是我的函数”

我可以使用 importlib.machinery.SourceFileLoader 来做到这一点,但它导入了一些我不想要的 python 库。有什么办法可以实现这一点吗?正则表达式是一种解决方案,但如果变量名称发生更改,则可能会出现问题。有没有更好的方法来做到这一点?

最佳答案

假设 my_functiontest.py 中没有其他依赖项,您可以使用 ast.parse 将文件解析为 AST 树,使用ast.walk遍历节点,查找namemy_functionFunctionDef节点,编​​译在节点周围添加 Module 节点后,执行编译后的代码对象,以便该函数可以在当前命名空间中可用:

import pkgutil
import ast
with open(pkgutil.get_loader('test').get_filename()) as file:
    for node in ast.walk(ast.parse(file.read())):
        if isinstance(node, ast.FunctionDef) and node.name == 'my_function':
            exec(compile(ast.Module(body=[node]), '', 'exec'))

这样如果test.py包含:

import foobar
def my_function(a):
    return a + 1
bomb = 0 / 0 # bad stuff. importing this will raise an exception.

运行上面的示例代码后,my_function(2)将返回:3

关于python - 如何在没有导入库的情况下获取python文件中的函数定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55541571/

相关文章:

python - 将实例方法传递到 python 多处理进程中

python - geopandas overlay() 函数在 QGIS 中不起作用

Python 命名约定——namedtuples

python - 连接/合并每个 Json 文件,python

Python Nostest ValueError 异常

python - Travis 作业报告成功,即使测试失败(使用 tox)

python - 无法将 RDD 转换为 DataFrame(RDD 有数百万行)

Python:YACC 的问题

python-3.x - 本地目录遮蔽第 3 方包

python-3.x - Python 3.4错误 "Unicode-objects must be encoded before hashing"