我有一个包含内容的文件 test.py 。文件结构定义如下。我无法控制文件的结构。
import *some python libraries*
def my_function:
content = "This is my function"
return content
我想编写一段代码来读取这个 python 文件并返回函数 my_function 的返回值,即“这是我的函数”
我可以使用 importlib.machinery.SourceFileLoader 来做到这一点,但它导入了一些我不想要的 python 库。有什么办法可以实现这一点吗?正则表达式是一种解决方案,但如果变量名称发生更改,则可能会出现问题。有没有更好的方法来做到这一点?
最佳答案
假设 my_function
在 test.py
中没有其他依赖项,您可以使用 ast.parse
将文件解析为 AST 树,使用ast.walk遍历节点,查找name
为my_function
的FunctionDef
节点,编译在节点周围添加 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/