有没有办法从python解释器查看函数,类或模块的源代码?(除了使用帮助查看文档和dir以查看属性/方法)
Ben*_*ier 17
如果你打算以交互方式使用python,那么很难击败ipython.要打印任何已知功能的来源,您可以使用%psource.
In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"
Run Code Online (Sandbox Code Playgroud)
输出甚至着色.您也可以直接$EDITOR使用定义源文件调用您的%edit.
In [3]: %edit ctypes.c_bool
Run Code Online (Sandbox Code Playgroud)
Dun*_*can 10
>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An IOError is
raised if the source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4927 次 |
| 最近记录: |