-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcodegen.py
More file actions
executable file
·74 lines (62 loc) · 2.06 KB
/
codegen.py
File metadata and controls
executable file
·74 lines (62 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# # # # # # # # # # # # #
# Create a code object #
# # # # # # # # # # # # #
"""
>>> from types import CodeType
>>> help(CodeType)
Help on class code in module builtins:
class code(object)
| code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,
| constants, names, varnames, filename, name, firstlineno,
| lnotab[, freevars[, cellvars]])
|
| Create a code object. Not for the faint of heart.
...
"""
from types import CodeType
from dis import dis
import sys
if sys.version_info.major < 3:
print("You need python 3 to run this code.")
sys.exit(1)
co_code = bytes([101, 0, 0, #Load print function
101, 1, 0, #Load name 'a'
101, 2, 0, #Load name 'b'
23, #Take first two stack elements and store their sum
131, 1, 0, #Call first element in the stack with one positional argument
1, #Pop top of stack
101, 0, 0, #Load print function
101, 1, 0, #Load name 'a'
101, 2, 0, #Load name 'b'
20, #Take first two stack elements and store their product
131, 1, 0, #Call first element in the stack with one positional argument
1, #Pop top of stack
100, 0, 0, #Load constant None
83]) #Return top of stack
lnotab = bytes([14,1])
my_code = CodeType(
0,
0,
0,
3,
64,
co_code,
(None,),
('print', 'a', 'b'),
(),
'my_code_filename',
'my_code',
1,
lnotab,
freevars=(),
cellvars=() )
def main():
a=2
b=7
print('Print the sum and the product of a=%s and b=%s:' % (a, b))
exec(my_code) # code prints the sum and the product of "a" and "b"
print('\nDisassemble the code:')
dis(my_code) # disassemble the code
if __name__ == '__main__':
main()