本文整理汇总了Python中opcode.opname方法的典型用法代码示例。如果您正苦于以下问题:Python opcode.opname方法的具体用法?Python opcode.opname怎么用?Python opcode.opname使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类opcode
的用法示例。
在下文中一共展示了opcode.opname方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format_start
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def format_start(self, event):
if event.frame_info.is_ipython_cell:
return []
if event.comprehension_type:
return [u'{type}:'.format(type=event.comprehension_type)]
else:
if event.event == 'enter':
description = 'Enter with block in'
else:
assert event.event == 'call'
if event.frame_info.is_generator:
if event.opname == 'YIELD_VALUE':
description = 'Re-enter generator'
else:
description = 'Start generator'
else:
description = 'Call to'
return [
u'{c.cyan}>>> {description} {name} in File "{filename}", line {lineno}{c.reset}'.format(
name=event.code_qualname(),
filename=_get_filename(event),
lineno=event.line_no,
c=self.c,
description=description,
)]
示例2: common_instructions
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def common_instructions(profile):
"""Returns the most common opcodes in order of descending frequency.
The result is a list of tuples of the form
(opcode, opname, # of occurrences)
"""
if has_pairs(profile) and profile:
inst_list = profile[-1]
else:
inst_list = profile
result = [(op, opcode.opname[op], count)
for op, count in enumerate(inst_list)
if count > 0]
result.sort(key=operator.itemgetter(2), reverse=True)
return result
示例3: common_pairs
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def common_pairs(profile):
"""Returns the most common opcode pairs in order of descending frequency.
The result is a list of tuples of the form
((1st opcode, 2nd opcode),
(1st opname, 2nd opname),
# of occurrences of the pair)
"""
if not has_pairs(profile):
return []
result = [((op1, op2), (opcode.opname[op1], opcode.opname[op2]), count)
# Drop the row of single-op profiles with [:-1]
for op1, op1profile in enumerate(profile[:-1])
for op2, count in enumerate(op1profile)
if count > 0]
result.sort(key=operator.itemgetter(2), reverse=True)
return result
示例4: collect_version_info
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def collect_version_info():
pyenv_root = subprocess.check_output(['pyenv', 'root']).decode('latin1').split('\n')[0]
versions = subprocess.check_output(['pyenv', 'versions', '--bare']).decode('latin1')
version_info = {}
for py_version in versions.split():
version = tuple(map(int, py_version.split('.')[:3]))
if (3, 5, 2) <= version < (3, 6, 0):
version = 352
else:
version = version[0] * 100 + version[1] * 10
if version not in STACK_EFFECT:
print('Skipping %s' % py_version, file=sys.stderr)
continue
py_executable = os.path.join(pyenv_root, 'versions', py_version, 'bin', 'python')
try:
if py_version.startswith('3'):
output = subprocess.check_output([py_executable, '-c', SCRIPT_PY3]).decode('ascii')
else:
output = subprocess.check_output([py_executable, '-c', SCRIPT_PY2]).decode('ascii')
except:
print('%s failed' % py_version, file=sys.stderr)
continue
version_data = version_info[version] = eval(output)
opnames = version_data['opname']
version_data.update({
'stackeffect': dict((k, v) for k, v in six.iteritems(STACK_EFFECT[version]) if k in opnames),
'stackeffect_traits': STACK_TRAITS[version],
})
return version_info
示例5: visit
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def visit(self, index, op, arg=None, lineno=None, cflow_in=False):
"""
Callback of the visitor. It dynamically constructs the name
of the specialized visitor to call based on the name of the opcode.
:param index: Bytecode index.
:param op: The opcode that is currently visited.
:param arg: The expanded oparg (i.e., constants, names, etc. are resolved).
:param lineno: The line number associated with the opcode.
:param cflow_in: ``True`` if the current ``index`` is the target of a jump.
"""
# Let's start with a slow impl of the jump table, with
# reflection
method_name = BytecodeVisitor.toMethodName(opcode.opname[op])
if hasattr(self, method_name):
meth = getattr(self, method_name)
if op < opcode.HAVE_ARGUMENT:
logger.debug("%03d %26s" % (lineno, method_name))
return meth()
else:
logger.debug("%03d %26s( %s )" % (lineno, method_name, repr(arg)))
return meth(arg)
else:
logger.error("Method not found: %s" % method_name)
# 2.7 specific visitors. See https://docs.python.org/2/library/dis.html
示例6: show_bytecode
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def show_bytecode(bytecode, start=0, end=2**32):
from ..analysis.python.effects import get_stack_effect
if bytecode is None:
return ''
buffer = []
j = start
end = min(end, len(bytecode) - 1)
while j <= end:
index, lineno, op, arg, _, co = bytecode[j]
uid = hex(id(co))[-5:]
pop_push_str = ''
try:
pop, push = get_stack_effect(op, arg)
pop_push_str = ' (-%d +%d) ' % (pop, push)
except ValueError, ex:
pop_push_str = ' '
if op >= opcode.HAVE_ARGUMENT:
rts = repr(arg)
if len(rts) > 40:
rts = rts[:40] + '[...]'
jump_target = ''
if op in opcode.hasjrel or op in opcode.hasjabs:
jump_address = arg if op in opcode.hasjabs else index + arg + 3
jump_target = ' -------------> (%4d)' % jump_address
buffer.append("[%5s]%4d(%4d) %20s(%3d)%s (%s)%s"
% (uid, lineno, index, opcode.opname[op], op, pop_push_str, rts, jump_target))
else:
buffer.append("[%5s]%4d(%4d) %20s(%3d)%s"
% (uid, lineno, index, opcode.opname[op], op, pop_push_str))
j += 1
示例7: convert_ast_constraint
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def convert_ast_constraint(ast_node):
"""
Returns a new ``Expr`` node.
:param ast_node: The current AST node in the conditional.
"""
op, arg = ast_node.data
if op in OP_MAP:
# We got an operator
return Operator.fromOpcode(op, arg)
elif op == COMPARE_OP and arg in CMP_MAP:
return Comparator.fromOpcode(op, arg)
elif op in LOAD_OPCODES:
if op == LOAD_CONST:
return Const.fromValue(arg)
else:
if arg in ('True', 'False', 'None', 'str', 'int', 'bool', 'chr', 'float', 'tuple'):
return Const.fromValue(arg, is_symbol=True)
return Ref.fromName(arg)
elif op in CALL_OPCODES:
if is_type_check(ast_node):
return Comparator.fromKind(CMP_TYPE_CHECK)
elif is_type_cast(ast_node):
return Operator.fromTypeMethod(ast_call_node.first_child.data[1])
else:
return Undef(data=ast_node.data)
else:
logger.debug("Not converted node: op=%s, arg=%s", opcode.opname[op], repr(arg))
return Undef(data=ast_node.data)
示例8: opname
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def opname(self):
code_byte = self.code.co_code[self.frame.f_lasti]
if not isinstance(code_byte, int):
code_byte = ord(code_byte)
return opcode.opname[code_byte]
示例9: format_return
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def format_return(self, event):
# If a call ends due to an exception, we still get a 'return' event
# with arg = None. This seems to be the only way to tell the difference
# https://stackoverflow.com/a/12800909/2482744
opname = event.opname
arg = event.arg
if arg is None:
if opname == 'END_FINALLY':
if event.frame_info.had_exception:
return [u'{c.red}??? Call either returned None or ended by exception{c.reset}'
.format(c=self.c)]
elif opname not in ('RETURN_VALUE', 'YIELD_VALUE'):
return [u'{c.red}!!! Call ended by exception{c.reset}'.format(c=self.c)]
value = self.highlighted(my_cheap_repr(arg))
if event.comprehension_type:
prefix = plain_prefix = u'Result: '
else:
plain_prefix = u'<<< {description} value from {func}: '.format(
description='Yield' if opname == 'YIELD_VALUE' else 'Return',
func=event.code_qualname(),
)
prefix = u'{c.green}{}{c.reset}'.format(
plain_prefix,
c=self.c,
)
return indented_lines(prefix, value, plain_prefix=plain_prefix)
示例10: render_common_pairs
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def render_common_pairs(profile=None):
"""Renders the most common opcode pairs to a string in order of
descending frequency.
The result is a series of lines of the form:
# of occurrences: ('1st opname', '2nd opname')
"""
if profile is None:
profile = snapshot_profile()
def seq():
for _, ops, count in common_pairs(profile):
yield "%s: %s\n" % (count, ops)
return ''.join(seq())
示例11: __str__
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def __str__(self):
mark = "*" if self in self.code.else_jumps else " "
return "{} {} {} {}".format(
mark, self.addr,
opname[self.opcode], self.arg or ""
)
示例12: run
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def run(self):
addr, end_addr = self.start_addr, self.end_addr
while addr and addr < end_addr:
opcode, arg = addr
method = getattr(self, opname[opcode])
if arg is None:
new_addr = method(addr)
else:
new_addr = method(addr, arg)
if new_addr is self.END_NOW:
break
elif new_addr is None:
new_addr = addr[1]
addr = new_addr
return addr
示例13: COMPARE_OP
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def COMPARE_OP(self, addr, opname):
left, right = self.stack.pop(2)
if opname != 10: # 10 is exception match
self.stack.push(PyCompare([left, cmp_op[opname], right]))
else:
# It's an exception match
# left is a TryStatement
# right is the exception type to be matched
# It goes:
# COMPARE_OP 10
# POP_JUMP_IF_FALSE <next except>
# POP_TOP
# POP_TOP or STORE_FAST (if the match is named)
# POP_TOP
# SETUP_FINALLY if the match was named
assert addr[1].opcode == POP_JUMP_IF_FALSE
left.next_start_except = addr[1].jump()
assert addr[2].opcode == POP_TOP
assert addr[4].opcode == POP_TOP
if addr[5].opcode == SETUP_FINALLY:
except_start = addr[6]
except_end = addr[5].jump()
else:
except_start = addr[5]
except_end = left.next_start_except[-1]
d_body = SuiteDecompiler(except_start, except_end)
d_body.run()
left.add_except_clause(right, d_body.suite)
if addr[3].opcode != POP_TOP:
# The exception is named
d_exc_name = SuiteDecompiler(addr[3], addr[4])
d_exc_name.stack.push(left)
# This will store the name in left:
d_exc_name.run()
# We're done with this except clause
return self.END_NOW
#
# Stack manipulation
#
示例14: decode_codeobj
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def decode_codeobj(codeobj):
# adapted from dis.dis
extended_arg = 0
if is_py3k:
codestr = codeobj.co_code
else:
codestr = [ord(ch) for ch in codeobj.co_code]
free = None
i = 0
while i < len(codestr):
op = codestr[i]
opname = opcode.opname[op]
i += 1
argval = None
if op >= opcode.HAVE_ARGUMENT:
oparg = codestr[i] + codestr[i + 1] * 256 + extended_arg
i += 2
extended_arg = 0
if op == opcode.EXTENDED_ARG:
extended_arg = oparg * 65536
continue
if op in opcode.hasconst:
argval = codeobj.co_consts[oparg]
elif op in opcode.hasname:
argval = codeobj.co_names[oparg]
elif op in opcode.hasjrel:
argval = i + oparg
elif op in opcode.haslocal:
argval = codeobj.co_varnames[oparg]
elif op in opcode.hascompare:
argval = opcode.cmp_op[oparg]
elif op in opcode.hasfree:
if free is None:
free = codeobj.co_cellvars + codeobj.co_freevars
argval = free[oparg]
yield (opname, argval)
示例15: _extract_target_of_assignment
# 需要导入模块: import opcode [as 别名]
# 或者: from opcode import opname [as 别名]
def _extract_target_of_assignment():
frame = sys._getframe(3)
code = frame.f_code
next_instruction = code.co_code[frame.f_lasti+2]
instruction_arg = code.co_code[frame.f_lasti+3]
instruction_name = opcode.opname[next_instruction]
if instruction_name == 'STORE_FAST':
return code.co_varnames[instruction_arg]
elif instruction_name in ['STORE_NAME', 'STORE_GLOBAL']:
return code.co_names[instruction_arg]
elif instruction_name in ['LOAD_FAST', 'LOAD_NAME', 'LOAD_GLOBAL'] and \
opcode.opname[code.co_code[frame.f_lasti+4]] in ['LOAD_CONST', 'LOAD_FAST'] and \
opcode.opname[code.co_code[frame.f_lasti+6]] == 'STORE_SUBSCR':
base_name = (code.co_varnames if instruction_name == 'LOAD_FAST' else code.co_names)[instruction_arg]
second_instruction = opcode.opname[code.co_code[frame.f_lasti+4]]
second_arg = code.co_code[frame.f_lasti+5]
if second_instruction == 'LOAD_CONST':
value = code.co_consts[second_arg]
elif second_instruction == 'LOAD_FAST':
var_name = code.co_varnames[second_arg]
value = frame.f_locals[var_name]
else:
value = None
if type(value) is int:
index_name = str(value)
return base_name + '[' + index_name + ']'
else:
return None
elif instruction_name == 'RETURN_VALUE':
return 'return'
else:
return None