![](/img/trans.png)
[英]Previewing the class or function definition source code in the interactive shell
[英]Display function definition in interactive shell
我在 Python 交互式 Shell(Windows XP 下的 ActiveState ActivePython 2.6.4)中工作。 我创建了一个可以满足我需求的函数。 但是,我已经清除了屏幕,所以我无法返回查看函数定义。 它也是一个多行函数,因此重新显示行的向上箭头的值最小。 无论如何要返回函数的实际代码吗? dir() 显示了“ code ”和“func_code”属性,但我不知道它们是否包含我需要的内容。
不, __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 等平台上。
已经很长时间了,但可能有人需要它。 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
不,不是。 您可以将 yourfunc.func_code.co_code (实际编译的字节码)写入文件,然后尝试使用 decompyle 或 unpyc 对其进行反编译,但这两个项目都很旧且无人维护,并且从未很好地支持反编译。
将您的函数简单地写入文件开始变得非常容易。
除非有办法在 activestate shell 上执行此操作,否则无法检索您在 shell 上键入的确切代码。 至少在 Linux 上,使用 CPython 提供的 Python Shell 没有特殊的方法可以实现这一点。 也许使用 iPython。
func_code 属性是一个代表函数字节码的对象,你可以从这个对象中得到的唯一东西是字节码本身,而不是“原始”代码。
您可以尝试按“ctrl+r”(即我在 bash 中反向搜索)然后输入
def <name of your function>
然后按 enter ,它可能会显示函数定义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.