你可以试试inspect.getsource()
。但是,它并不总是有效。
ipython中的示例:
In [1]: import inspect
In [2]: def foo():
...: print 'hello'
...:
In [3]: inspect.getsource(foo)
Out[3]: u"def foo():\n print 'hello'\n"
在 ipython 中,在导入检查之前或之后定义函数并不重要:
In [1]: def foo():
...: print 'hello'
...:
In [2]: import inspect
In [3]: inspect.getsource(foo)
Out[3]: u"def foo():\n print 'hello'\n"
在基本的 cpython 交互式提示中,它根本不起作用;
Python 2.7.3 (default, Jul 26 2012, 19:08:05)
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
... print 'hello'
...
>>> import inspect
>>> inspect.getsource(foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/local/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/local/lib/python2.7/inspect.py", line 538, in findsource
raise IOError('could not get source code')
IOError: could not get source code
>>> def bar():
... print 'second try'
...
>>> inspect.getsource(bar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/local/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/local/lib/python2.7/inspect.py", line 538, in findsource
raise IOError('could not get source code')
IOError: could not get source code
我没有尝试 IDLE,因为我基本上从不使用它。我更喜欢 ipython 进行交互式实验和使用 emacs 进行编辑。