python运行中更改代码_运行时更改python源代码

以下模块可能会更改您需要的任何内容,这并不是说使用它是一个好主意,而不是到处乱跑:)

请注意,它不会更改您的源代码,这可能是一个灾难,特别是如果您犯了编码错误。“更安全”的选择是和byteplay玩Ok, now let's play! Say we want to change the function, to print its arguments in reverse order. To do this, we will add a ROT_TWO opcode after the two arguments were loaded to the stack. See how simple it is:>>> from byteplay import *

>>> from pprint import pprint

>>> def f(a, b):

... print (a, b)

...

>>> f(3, 5)

(3, 5)

>>> c = Code.from_code(f.func_code)

>>> c.code[3:3] = [(ROT_TWO, None)]

>>> f.func_code = c.to_code()

>>> f(3, 5)

(5, 3)

>>> f(3, 5)

(5, 3)

如果您使用的是一组已定义的选项,但希望保留相同的函数调用,您还可以执行以下操作class Foo(object):

def fn(self):

pass

def op1(self):

print "HELLO"

#etc

>>> a = Foo()

>>> a.fn()

>>> a.fn = a.op1

>>> a.fn()

HELLO

你可能感兴趣的:(python运行中更改代码)