[英]Get the list of local functions from a python file into another python file
I have a requirement where I need to parse the functions defined in a python file from another python file. 我有一个需要从另一个python文件解析python文件中定义的函数的要求。
eg I have a python file with following contents: 例如,我有一个包含以下内容的python文件:
a.py
import os, sys
def function1('text'):
pass
def function2('text'):
pass
Another file is: b.py 另一个文件是:b.py
interested_func = 'function2'
function_list = <code to fetch the functions defined in a.py>
if interested_func in function_list:
print 'match found'
How can I get the functions from a.py into b.py so that I can compare the same with the 'interested_func' data and can do specific task based on the match. 如何将函数从a.py转换为b.py,以便可以将它们与“ interested_func”数据进行比较,并可以根据匹配结果执行特定任务。
Please note that I have 100s of files with different functions defined inside them, so I do not want to import the file. 请注意,我有100多个文件,其中定义了不同的功能,所以我不想导入该文件。
Please help, thanks in advance! 请帮助,在此先感谢!
You should probably use the importlib
module: 您可能应该使用importlib
模块:
import importlib
obj = importlib.import_module(module)
print(dir(obj))
You can read more about importlib over in the Python docs . 您可以在Python文档中阅读有关importlib的更多信息。
If that doesn't work for you, then you'll probably want to look at some static code analysis tools such as pylint that might give you a clue into how to do this sort of thing. 如果这对您不起作用,那么您可能希望查看一些静态代码分析工具,例如pylint,这些工具可能会为您提供有关如何执行此类操作的线索。 Another place to look would be to check out PyDev's source code and see how it does code analysis. 另一个值得一看的地方是查看PyDev的源代码,并查看其如何进行代码分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.