有时我们想知道某些函数的源代码是什么样子或它们在哪里,或者我们需要将源代码作为字符串进行操作。 在这种情况下,我们需要一种方便的方法来检索Python函数的源代码。
检查
inspect
是一个内置库。 在计算机上安装Python之后,它已经存在。 inspect
模块提供了几个有用的功能,以帮助您获取有关活动对象的信息,例如模块,类,方法,函数,回溯,框架对象和代码对象。 在其众多功能中,其检索功能源代码的能力十分突出。
In [1]: |
import pandas
import
inspect
|
In [3]: |
source_DF
=
inspect .
getsource
( pandas.
DataFrame
)
print
(
type
( source_DF
)
)
<<class 'str'>> |
In [4]: | print ( len ( source_DF ) )
218432 |
In [5]: | print ( source_DF [ : 200 ] )
class DataFrame(NDFrame):
""" Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row a with labeled axes (rows and columns). Arithmetic operations align on both row a |
In [6]: |
source_file_DF
=
inspect .
getsourcefile
( pandas.
DataFrame
)
print
( source_file_DF
)
D:\Users\dengdong\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py |
In [7]: |
sourcelines_DF
=
inspect .
getsourcelines
( pandas.
DataFrame
)
print
(
type
( sourcelines_DF
)
)
print
(
len
( sourcelines_DF
)
)
print
(
type
( sourcelines_DF
[
0
]
)
)
<class 'tuple'> 2 <class 'list'> |
在IPython或Jupyter中 ,我们还可以使用此方法来检索在控制台中定义的函数的源代码。
In [9]: |
def
test
( x
) :
return x*
2
print
(
inspect .
getsource
(
test
)
)
def test(x): return x*2 |
In [10]: |
print
(
inspect .
getsourcefile
(
test
)
)
<ipython-input-9-70ac3e17460c> |
In [11]: | print ( inspect . getsourcelines ( test ) )
(['def test(x):\n', ' return x*2\n'], 1) |
请注意,检索自定义函数的源代码仅在IPython或Jupyter中有效。 如果我们使用普通的Python并以交互方式定义函数,则会遇到错误IOError: could not get source code
,也将无法检索源代码。 这是因为其设置仅支持从文件加载的对象,而不支持交互式会话。
莳萝
dill
扩展了Python的pickle
模块,用于将Python对象序列化和反序列化为大多数内置的Python类型。 同时,它还可以检索Python对象的源代码。 请注意, dill
不是标准库,因此必须单独安装。
它的API与inspect
的非常相似。
In [6]: |
import dill
source_DF
= dill.
source .
getsource
( pandas.
DataFrame
)
print
(
type
( source_DF
)
)
print
(
len
( source_DF
)
)
print
( source_DF
[ :
200
]
)
source_file_DF
= dill.
source .
getsourcefile
( pandas.
DataFrame
)
print
( source_file_DF
)
sourcelines_DF
= dill.
source .
getsourcelines
( pandas.
DataFrame
)
print
(
type
( sourcelines_DF
)
)
print
(
len
( sourcelines_DF
)
)
print
(
type
( sourcelines_DF
[
0
]
)
)
<
type
'str'
>
195262
class DataFrame
( NDFrame
) :
""" Two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). Arithmetic operations
align on both row a
/Users/XD/anaconda/lib/python2.7/site-packages/pandas/core/frame.py
<type 'tuple'>
2
<type 'list'>
|
但是, dill
和inspect
之间的最大区别是dill
的检索功能在普通的Python控制台中支持自定义对象。
翻译自: https://opensource.com/article/18/5/how-retrieve-source-code-python-functions