Skip to content

Instantly share code, notes, and snippets.

@VMois
Last active October 24, 2023 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VMois/f7398077fb5dd46a45129dad142d81a5 to your computer and use it in GitHub Desktop.
Save VMois/f7398077fb5dd46a45129dad142d81a5 to your computer and use it in GitHub Desktop.
Dummy Python VM - a small example of running your Python programs... in Python
import dis
source_py = 'my_best_code.py'
stack = []
namespace = {
'print': print,
}
with open(source_py) as f_source:
source_code = f_source.read()
byte_code = compile(source_code, source_py, 'exec')
code = dis.Bytecode(byte_code)
for op in code:
if op.opname == 'LOAD_CONST':
stack.append(op.argval)
elif op.opname == 'STORE_NAME':
value = stack.pop()
namespace[op.argval] = value
elif op.opname == 'LOAD_NAME':
value = namespace[op.argval]
stack.append(value)
elif op.opname == 'BINARY_ADD':
b = stack.pop()
a = stack.pop()
stack.append(a + b)
elif op.opname == 'CALL_FUNCTION':
value = stack.pop()
func = stack[-1]
func(value)
elif op.opname == 'POP_TOP':
stack.pop()
elif op.opname == 'RETURN_VALUE':
print(f'Program finished with value: {stack.pop()}')
a = 5
b = 6
c = a + b
print(c + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment