Python3.4打开一个python文件并查找函数名

2024-03-29 14:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

打开Python文件以便通过

read_file = open(input_file, "r"))

如何从打开的python文件中找到函数名并打印它们?你知道吗


Tags: 文件函数readinputopenfile
2条回答

ast救命!你知道吗

import ast

with open('somefile.py', 'r') as fin:
    source = fin.read()

tree = ast.parse(source)

class FuncFinder(ast.NodeVisitor):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.function_names = []


    def visit_FunctionDef(self, node):
        self.function_names.append(node.name)
        self.generic_visit(node)

finder = FuncFinder()
finder.visit(tree)
print(finder.function_names)

可复制/粘贴的工作演示:

source = """
def foo():
  pass

def bar():
  pass

class FooBar(object):
  def __init__(self):
    pass
"""

import ast

tree = ast.parse(source)

class FuncFinder(ast.NodeVisitor):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.function_names = []


    def visit_FunctionDef(self, node):
        self.function_names.append(node.name)
        self.generic_visit(node)

finder = FuncFinder()
finder.visit(tree)
print(finder.function_names)  # ['foo', 'bar', '__init__']

注意,我们得到所有的函数名(包括类中的、嵌套在其他函数中的等)。您可以通过添加def visit_ClassDef(self, node): pass轻松跳过这些内容。。。你知道吗

使用^{}

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

>>> read_file = open('test.txt', 'r')
>>> dir(read_file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

相关问题 更多 >