- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个工具来分析用户定义函数定义中使用的代码,例如:
def help_fun(a, b): return a * b
def test1(numbers):
r1, r2 = np.multiply.reduce(numbers), sum(numbers)/len(numbers)
r = math.sin(help_fun(r1, r2))
return math.sqrt(r)
不过,我明白,how to interpret dis.dis(test1)
的结果:
3 0 LOAD_GLOBAL 0 (np)
2 LOAD_ATTR 1 (multiply)
4 LOAD_METHOD 2 (reduce)
6 LOAD_FAST 0 (numbers)
8 CALL_METHOD 1
10 LOAD_GLOBAL 3 (sum)
...
5 46 LOAD_GLOBAL 5 (math)
48 LOAD_METHOD 8 (sqrt)
50 LOAD_FAST 3 (r)
52 CALL_METHOD 1
54 RETURN_VALUE
我期望的输出是:
{0: {'functions': ['sum', 'len', 'help_fun'],
'methods': ['np.multiply.reduce', 'math.sin', 'math.sqrt']}} #frame 0: scope of test1
为了收集函数和方法名称,我对反汇编器堆栈的内容进行了包装,并使用特定的方式从堆栈存档中提取这些名称。
import types
import dis
def get_frames(code):
'''given <function>.__code__ instance, iterate each code frame
>>> [type(x) for x in get_frames(test1.__code__)]
[code]
'''
yield code
for c in code.co_consts:
if isinstance(c, types.CodeType):
yield from get_frames(c)
break
def get_calls(instructions, stack):
'''get called functions and methods in CALL_FUNCTION and CALL_METHOD opnames'''
functions, methods = [], []
for idx, instr in enumerate(instructions):
if instr.opname == 'CALL_FUNCTION':
functions.append(stack[idx - 1][- 1 - instr.arg])
elif instr.opname == 'CALL_METHOD':
methods.append(stack[idx - 1][- 1 - instr.arg])
return {'functions': functions, 'methods': methods}
def get_stack(instructions):
'''Wrapper for stack contents'''
stack = []
for n in instructions:
if n.opname in ('LOAD_FAST', 'LOAD_GLOBAL', 'LOAD_CONST'):
stack.append(n.argrepr) #global var
elif n.opname in ('LOAD_METHOD', 'LOAD_ATTR'):
stack[-1] = f'{stack[-1]}.{n.argrepr}'
elif n.opname in ('CALL_FUNCTION', 'CALL_METHOD'):
args = stack[-n.arg:]
del stack[-n.arg:]
stack[-1] = f'{stack[-1]}({", ".join(args)})'
elif n.opname == 'BINARY_TRUE_DIVIDE':
stack[-2:] = [' / '.join(stack[-2:])]
elif n.opname == 'STORE_FAST':
del stack[-1]
elif n.opname == 'ROT_TWO':
stack[-1], stack[-2] = stack[-2], stack[-1]
elif n.opname == 'GET_ITER':
stack[-1] = f'iter({stack[-1]})'
yield stack.copy()
code = list(get_frames(test1.__code__))
out = dict()
for i, c in enumerate(code):
instructions = dis.Bytecode(c)
stack = list(get_stack(instructions))
out[i] = get_calls(instructions, stack)
out
>>> {0: {'functions': ['sum', 'len', 'help_fun'], 'methods': ['np.multiply.reduce', 'math.sin', 'math.sqrt']}}
在我的方法中,函数和方法的名称是从 stack
中提取的表格列:
| line | opname | arg | argrepr | stack |
|--------|--------------------|-------|-----------|----------------------------------------------------------|
| 3 | LOAD_GLOBAL | 0 | np | np |
| | LOAD_ATTR | 1 | multiply | np.multiply |
| | LOAD_METHOD | 2 | reduce | np.multiply.reduce |
| | LOAD_FAST | 0 | numbers | np.multiply.reduce, numbers |
| | CALL_METHOD | 1 | | np.multiply.reduce(numbers) |
| | LOAD_GLOBAL | 3 | sum | np.multiply.reduce(numbers), sum |
| | LOAD_FAST | 0 | numbers | np.multiply.reduce(numbers), sum, numbers |
| | CALL_FUNCTION | 1 | | np.multiply.reduce(numbers), sum(numbers) |
| | LOAD_GLOBAL | 4 | len | np.multiply.reduce(numbers), sum(numbers), len |
| | LOAD_FAST | 0 | numbers | np.multiply.reduce(numbers), sum(numbers), len, numbers |
| | CALL_FUNCTION | 1 | | np.multiply.reduce(numbers), sum(numbers), len(numbers) |
| | BINARY_TRUE_DIVIDE | | | np.multiply.reduce(numbers), sum(numbers) / len(numbers) |
| | ROT_TWO | | | sum(numbers) / len(numbers), np.multiply.reduce(numbers) |
| | STORE_FAST | 1 | r1 | sum(numbers) / len(numbers) |
| | STORE_FAST | 2 | r2 | |
| 4 | LOAD_GLOBAL | 5 | math | math |
| | LOAD_METHOD | 6 | sin | math.sin |
| | LOAD_GLOBAL | 7 | help_fun | math.sin, help_fun |
| | LOAD_FAST | 1 | r1 | math.sin, help_fun, r1 |
| | LOAD_FAST | 2 | r2 | math.sin, help_fun, r1, r2 |
| | CALL_FUNCTION | 2 | | math.sin, help_fun(r1, r2) |
| | CALL_METHOD | 1 | | math.sin(help_fun(r1, r2)) |
| | STORE_FAST | 3 | r | |
| 5 | LOAD_GLOBAL | 5 | math | math |
| | LOAD_METHOD | 8 | sqrt | math.sqrt |
| | LOAD_FAST | 3 | r | math.sqrt, r |
| | CALL_METHOD | 1 | | math.sqrt(r) |
| | RETURN_VALUE | | | math.sqrt(r) |
但是,如果在我的说明中包含其他类型的操作名,事情会变得更加复杂。例如,如果使用了任何列表理解,我不确定堆栈的行为。获取方法和函数的名称可能会显示不正确的结果:
(<listcomp>
不是函数,而是我的包装器)
def test2(x):
return [[math.sqrt(m) for m in list(n)] for n in x]
预期输出:
{0: {'functions': [], 'methods': []}, #frame 0: scope of test2
1: {'functions': ['list'], 'methods': [], #frame 1: scope of <listcomp>
2: {'functions': [], 'methods': ['math.sqrt']}} #frame 2: scope of <listcomp>
当前代码的输出:
{0: {'functions': ["'test6.<locals>.<listcomp>'"], 'methods': []},
1: {'functions': ['list', "'test6.<locals>.<listcomp>.<listcomp>'"], 'methods': []},
2: {'functions': [], 'methods': ['math.sqrt']}}
它有时也可能会崩溃,因为我不确定堆栈发生了什么:
def test3(x,y):
return [pow(i,j) for i,j in zip(x,y)]
预期输出:
{0: {'functions': ['zip'], 'methods': []},
1: {'functions': ['pow'], 'methods': []}}
它在秒后崩溃 STORE_FAST
命令尝试从空堆栈中弹出项目。第二个范围的指令如下:
| line | opname | arg | argrepr | stack |
|--------|-----------------|-------|-----------|---------|
| 104 | BUILD_LIST | 0 | | |
| | LOAD_FAST | 0 | .0 | .0 |
| | FOR_ITER | 18 | to 24 | .0 |
| | UNPACK_SEQUENCE | 2 | | .0 |
| | STORE_FAST | 1 | i | |
| | STORE_FAST | 2 | j | ??? | ### stuck here
| | LOAD_GLOBAL | 0 | pow | ??? |
| | LOAD_FAST | 1 | i | ??? |
| | LOAD_FAST | 2 | j | ??? |
| | CALL_FUNCTION | 2 | | ??? |
| | LIST_APPEND | 2 | | ??? |
| | JUMP_ABSOLUTE | 4 | | ??? |
| | RETURN_VALUE | | | ??? |
有没有更简单的方法来获取调用者内部使用的方法和函数的名称?有没有更好的方法来获取堆栈存档?我知道,我对 get_stack
的实现目前很差,我正在寻找一种不同的方法或更好的堆栈控制文档。
备注
ls.append
最佳答案
如果您希望您的代码在 Python 版本之间更具可移植性,您应该考虑使用 ast .尽管 AST 确实会跨版本发生变化,但它通常以导致易于理解的错误的方式发生变化。
要修复您的代码,您将需要实现更多的操作。我通过忽略大多数事情并仅应用它们的堆栈效果(从堆栈中放置或移除的元素数量)来做到这一点。
import dis
import inspect
def iterate_stack(instructions):
stack = []
called = []
for instruction in instructions:
old_stack_len = len(stack)
if instruction.opname == "ROT_TWO":
stack[-1], stack[-2] = stack[-2], stack[-1]
elif instruction.opname == "ROT_THREE":
stack[-1], stack[-2], stack[-3] = stack[-2], stack[-3], stack[-1]
elif instruction.opname == "ROT_FOUR":
stack[-1], stack[-2], stack[-3], stack[-4] = stack[-2], stack[-3], stack[-4], stack[-1]
elif instruction.opname == "DUP_TOP":
stack.append(stack[-1])
elif instruction.opname == "DUP_TOP_TWO":
stack.extend(stack[-2:])
elif instruction.opname == "LOAD_ASSERTION_ERROR":
stack.append("AssertionError")
elif instruction.opname == "LOAD_NAME":
stack.append(instruction.argrepr)
elif instruction.opname == "LOAD_ATTR" or instruction.opname == "LOAD_METHOD":
if stack[-1]:
stack[-1] = stack[-1] + "." + instruction.argrepr
elif instruction.opname == "LOAD_GLOBAL":
stack.append(instruction.argrepr)
elif instruction.opname == "LOAD_FAST" or instruction.opname == "LOAD_CLOSURE" or instruction.opname == "LOAD_DEREF" or instruction.opname == "LOAD_CLASSDEREF":
if inspect.iscode(instruction.argval):
stack.append(None)
else:
stack.append(instruction.argrepr)
elif instruction.opname == "CALL_FUNCTION":
args = stack[-instruction.arg:]
del stack[-instruction.arg:]
if stack[-1] is not None:
called.append(f'{stack[-1]}({", ".join(args)})')
stack.pop()
elif instruction.opname == "CALL_FUNCTION_KW":
# TODO get the names of keyword arguments
called.append(stack[-1 - instruction.arg])
del stack[-1 - instruction.arg:]
stack.append(None)
elif instruction.opname == "CALL_FUNCTION_EX":
# TODO get the arguments
if instruction.arg & 0x01:
stack.pop()
stack.pop()
called.append(stack.pop())
elif instruction.opname == "CALL_METHOD":
# TODO get the arguments
called.append(stack[-2 - instruction.arg])
del stack[-2 - instruction.arg:]
stack.append(None)
elif instruction.opname == "ROT_N":
tos = stack.pop()
stack.insert(1 - instruction.arg, tos)
stack_effect = dis.stack_effect(instruction.opcode, instruction.arg)
while old_stack_len + stack_effect < len(stack):
stack.pop()
while old_stack_len + stack_effect > len(stack):
stack.append(None)
return called
def get_frames(code):
yield code
for c in code.co_consts:
if inspect.iscode(c):
yield from get_frames(c)
def help_fun(a, b):
return a * b
def test1(numbers):
r1, r2 = np.multiply.reduce(numbers), sum(numbers)/len(numbers)
r = math.sin(help_fun(r1, r2))
return math.sqrt(r)
def test2(x):
return [[math.sqrt(m) for m in list(n)] for n in x]
def test3(x,y):
return [pow(i,j) for i,j in zip(x,y)]
def main():
code = list(get_frames(test1.__code__))
out = dict()
for i, c in enumerate(code):
instructions = dis.get_instructions(c)
out[i] = iterate_stack(instructions)
print(out)
main()
这给出了所有三个示例的预期结果,在 Python 3.10.8(主要,2022 年 11 月 14 日,00:00:00)下 [GCC 12.2.1 20220819 (Red Hat 12.2.1-2 )] 在 Linux 上。它不会在 Python 3.11 上工作,因为字节码在每个版本中都会更改。
我真的不建议使用此代码,因为它会一直中断。您可能应该只构建一个 pylint 检查器,或者至少使用像 astroid 这样的库.
关于python - 如何在 Python 反汇编程序中访问堆栈的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74750427/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!