Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在没有导入库的情况下在python文件中获取函数定义?_Python_Python 3.x - Fatal编程技术网

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

如何在没有导入库的情况下在python文件中获取函数定义?,python,python-3.x,Python,Python 3.x,我有一个包含内容的test.py文件。文件结构定义如下。我无法控制文件的结构 import *some python libraries* def my_function: content = "This is my function" return content 我想写一段代码,读取这个python文件并返回函数my_的返回值,即“this is my function” 我可以使用importlib.machine.SourceFileLoader实现这一点,但它会导入

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

import *some python libraries*

def my_function:
    content = "This is my function"
    return content
我想写一段代码,读取这个python文件并返回函数my_的返回值,即“this is my function”


我可以使用importlib.machine.SourceFileLoader实现这一点,但它会导入一些我不想要的python库。我有没有办法做到这一点。Regex是一种解决方案,但如果变量名更改,则可能会出现问题。有没有更好的办法

如果
my_函数
test.py
中没有其他依赖项,您可以使用
ast.parse
将文件解析为ast树,使用
ast.walk
遍历节点,查找
FunctionDef
节点,其
名称
my_函数
,在节点周围添加
模块
节点后编译该节点,并执行编译后的代码对象,以便该函数可以在当前命名空间中使用:

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_函数(2)
将返回:
3

my_函数
放在一个不导入其他库的模块中。这不是解决方案。我无法控制python文件的内容,是的。更新了问题。删除不需要的导入是否会使
test.py
无法编译?也就是说,
test.py
中是否有依赖于不需要的库的变量或函数?我明白了,但至少
my_函数本身不依赖于不需要的库。对吗?