假设我有一个如下定义的Python函数:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

我可以使用foo.func_name获取函数的名称。我如何通过编程获得它的源代码,就像我上面键入的那样?


当前回答

扩展一下runeh的回答:

>>> def foo(a):
...    x = 2
...    return x + a

>>> import inspect

>>> inspect.getsource(foo)
u'def foo(a):\n    x = 2\n    return x + a\n'

print inspect.getsource(foo)
def foo(a):
   x = 2
   return x + a

编辑:正如@0sh指出的那样,这个例子使用ipython工作,而不是纯python。但是,当从源文件导入代码时,在这两种情况下都应该没问题。

其他回答

扩展一下runeh的回答:

>>> def foo(a):
...    x = 2
...    return x + a

>>> import inspect

>>> inspect.getsource(foo)
u'def foo(a):\n    x = 2\n    return x + a\n'

print inspect.getsource(foo)
def foo(a):
   x = 2
   return x + a

编辑:正如@0sh指出的那样,这个例子使用ipython工作,而不是纯python。但是,当从源文件导入代码时,在这两种情况下都应该没问题。

总结一下:

import inspect
print( "".join(inspect.getsourcelines(foo)[0]))

inspect模块有从python对象中检索源代码的方法。但是,似乎只有当源文件位于文件中时,它才有效。如果你有这个,我猜你就不需要从对象中获取源了。


下面使用Python 3.6测试inspect.getsource(foo):

import inspect

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

source_foo = inspect.getsource(foo)  # foo is normal function
print(source_foo)

source_max = inspect.getsource(max)  # max is a built-in function
print(source_max)

这是第一次印刷:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

然后在inspect.getsource(max)上失败,并出现以下错误:

TypeError: <built-in function max> is not a module, class, method, function, traceback, frame, or code object

你可以使用inspect模块来获得完整的源代码。你必须从inspect模块中使用getsource()方法。例如:

import inspect

def get_my_code():
    x = "abcd"
    return x

print(inspect.getsource(get_my_code))

你可以在下面的链接中查看更多选项。 检索python代码

我相信变量名没有存储在pyc/pyd/pyo文件中,因此如果没有源文件,就无法检索准确的代码行。