【问题标题】:Viewing the code of a Python function [duplicate]查看 Python 函数的代码 [重复]
【发布时间】:2010-10-25 12:56:39
【问题描述】:

假设我在 Python shell 中工作,我得到了一个函数 f。如何访问包含其源代码的字符串? (从 shell,而不是通过手动打开代码文件。)

我希望它甚至适用于在其他函数中定义的 lambda 函数。

【问题讨论】:

标签: python introspection


【解决方案1】:

inspect.getsource
看来getsource无法获取lambda的源代码。

【讨论】:

  • 是的,不幸的是,getsource 仅在它可以打开源代码所在的文件时才有效。您可以做的一件可能的事情是查看 lambda 正在做什么,即使用 dis 分解字节码。跨度>
【解决方案2】:

不一定是你要找的,但在ipython你可以做到:

>>> function_name??

您将获得函数的代码源(仅当它在文件中时)。所以这对 lambda 不起作用。但它绝对有用!

【讨论】:

    【解决方案3】:

    也许这会有所帮助(也可以获得 lambda,但它非常简单),

    import linecache
    
    def get_source(f):
    
        source = []
        first_line_num = f.func_code.co_firstlineno
        source_file = f.func_code.co_filename
        source.append(linecache.getline(source_file, first_line_num))
    
        source.append(linecache.getline(source_file, first_line_num + 1))
        i = 2
    
        # Here i just look until i don't find any indentation (simple processing).  
        while source[-1].startswith(' '):
            source.append(linecache.getline(source_file, first_line_num + i))
            i += 1
    
        return "\n".join(source[:-1])
    

    【讨论】:

      【解决方案4】:

      函数对象只包含编译后的字节码,不保留源文本。检索源代码的唯一方法是读取它来自的脚本文件。

      不过 lambda 并没有什么特别之处:它们仍然有一个 f.func_code.co_firstlineco_filename 属性,您可以使用它们来检索源文件,只要 lambda 是在文件中定义的而不是交互式输入。

      【讨论】:

      • 函数编译后的字节码可以用dis.dis查看。
      猜你喜欢
      • 1970-01-01
      • 2017-06-11
      • 2012-04-30
      • 2022-01-10
      相关资源
      最近更新 更多