[英]Add returned values to list in python?
When I print this I get: 当我打印时,我得到:
FuncA
FuncB
FuncC
When really what I want is: 当我真正想要的是:
['FuncA', 'FuncB', 'FuncC']
How would I be able to iterate through my returned values and add them to the list? 我将如何遍历返回的值并将它们添加到列表中?
Rather than manually look for text (which can easily lead to false positives), use the ast
module to build an abstract syntax tree, then extract function names with that: 与其手动查找文本(这很容易导致误报),不如使用ast
模块来构建抽象语法树,然后使用该语法提取函数名称:
import ast
functions = []
with open( 'codefile.py', 'r') as file:
tree = ast.parse(file.read(), 'codefile.py')
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
functions.append(node.name)
print(functions)
This finds all function objects anywhere in the source code, just like your search for def
text would have. 这将在源代码中的任何位置找到所有函数对象,就像搜索def
文本一样。 Except this skips commented out code or the word def
in a string literal, for instance. 除此之外,例如,跳过注释掉的代码或字符串文字中的单词def
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.