王剑编程网

分享专业编程知识与实战技巧

python散装笔记——142: 访问Python源代码和字节码

1: 显示函数的字节码

Python解释器在将代码传递到Python虚拟机上执行之前,会先将其编译为字节码(参见什么是Python字节码?)。

以下是如何查看Python函数的字节码:

import dis

def fib(n):
  if n <= 2: return 1
  return fib(n-1) + fib(n-2)

# 显示函数的反汇编字节码。
dis.dis(fib)

dis模块中的dis.dis函数将返回传递给它的函数的反编译字节码。

2: 显示对象的源代码

非内置对象

要打印Python对象的源代码,请使用inspect。注意,这不适用于内置对象,也不适用于交互式定义的对象。对于这些对象,您需要使用后面解释的其他方法。

以下是如何打印random模块中randint方法的源代码:

import random
import inspect

print(inspect.getsource(random.randint))

# 输出:
# def randint(self, a, b):
#     """Return random integer in range [a, b], including both end points.
#     """
#
#     return self.randrange(a, b+1)

仅打印文档字符串:

print(inspect.getdoc(random.randint))
# 输出:
# Return random integer in range [a, b], including both end points.

打印定义random.randint方法的文件的完整路径:

print(inspect.getfile(random.randint))

# c:\Python35\lib\random.py
print(random.randint.__code__.co_filename) # 与上述等效
# c:\Python35\lib\random.py

交互式定义的对象

如果对象是交互式定义的,inspect无法提供源代码,但您可以使用dill.source.getsource代替。

# 在交互式shell中定义一个新函数
def add(a, b):
    return a + b
print(add.__code__.co_filename)  # 输出:

import dill
print(dill.source.getsource(add))
# def add(a, b):
#     return a + b

内置对象

Python内置函数的源代码是用C语言编写的,只能通过查看Python的源代码来访问(托管在Mercurial上,或可从
https://www.python.org/downloads/source/下载)。

print(inspect.getsource(sorted)) # 抛出TypeError
type(sorted) # 

3: 探索函数的代码对象

CPython允许访问函数对象的代码对象。

__code__对象包含了函数的原始字节码(co_code),以及其他信息,如常量和变量名。

def fib(n):
  if n <= 2: return 1
  return fib(n-1) + fib(n-2)
dir(fib.__code__)

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言