在交互式 shell 中显示函数定义
我正在使用Python交互式命令行(在Windows XP下的ActiveState ActivePython 2.6.4)。我创建了一个函数,它能完成我想要的事情。不过,我清空了屏幕,所以无法回去查看这个函数的定义。这个函数还很长,所以用上箭头来重新显示代码行的效果也不太好。有没有办法能让我看到这个函数的实际代码呢?我在使用dir()命令时看到有“code”和“func_code”这两个属性,但我不知道它们是否包含我需要的内容。
5 个回答
1
不,实际上不是这样。你可以把你的函数的代码(也就是编译后的字节码)写到一个文件里,然后试着用 decompyle 或 unpyc 来反编译它们,但这两个工具都很老旧,而且没有人维护过,反编译的效果也不好。
其实,最简单的方法就是直接把你的函数写到一个文件里,这样开始就容易多了。
4
这已经有一段时间了,但可能会有人需要这个。getsource
可以用来获取源代码:
>>> def sum(a, b, c):
... # sum of three number
... return a+b+c
...
>>> from dill.source import getsource
>>>
>>> getsource(sum)
'def sum(a, b, c):\n # sum of three number\n return a+b+c\n'
要安装 dill
,你可以运行 pip install dill
。如果想要格式化它:
>>> fun = getsource(sum).replace("\t", " ").split("\n")
>>> for line in fun:
... print line
...
def sum(a, b, c):
# sum of three number
return a+b+c
14
不,__code__
和 func_code
是指编译后的字节码——你可以把它们拆解开来(可以用 dis.dis
),但无法恢复成原来的Python源代码。
可惜的是,源代码已经消失了,哪里也没有保存……:
>>> import inspect
>>> def f():
... print 'ciao'
...
>>> inspect.getsource(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 694, in getsource
lines, lnum = getsourcelines(object)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 683, in getsourcelines
lines, lnum = findsource(object)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 531, in findsource
raise IOError('could not get source code')
IOError: could not get source code
>>>
如果 inspect
也找不到,那就说明这个源代码真的没了。
如果你在使用GNU readline
的平台上(基本上除了Windows以外的任何平台),你可以利用 readline
记住一些“历史记录”的特点,把它写到一个文件里……:
>>> readline.write_history_file('/tmp/hist.txt')
然后再读取那个历史记录文件——不过,我不知道在Windows上怎么做到这一点。
你可能想用一些内存管理更好的IDE,而不是直接用“原始”的命令解释器,特别是在像Windows这样的系统上。