3

How can I execute code received from dis.dis() python?

import dis
class A():
    def __init__(self):
        print("hello")
dis.dis(A)
'''It returns:
  3           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
'''

I want something like this:

import dis
dis.run('''
  3           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
''')

i.e. Execute python disassembler.(I can execute .pyc from python ,can i execute disassembler?)

Soulis
  • 124
  • 1
  • 9
USERNAME GOES HERE
  • 692
  • 1
  • 15
  • 29
  • 3
    why do you want to do this? – Chris_Rands Jul 30 '19 at 12:41
  • I'm just interested in "how does python work?" and I wanna try to write python disassembler and run it for better understanding of "how does python work?" **P.S** Don't laugh!:) – USERNAME GOES HERE Jul 30 '19 at 13:02
  • You can't. dis.dis just gives you a human readable version of the assembly code. If you want to understand it below the hood I'd recommend directly learning asm or c. – blues Jul 30 '19 at 13:23
  • https://stackoverflow.com/questions/5287253/is-it-possible-to-decompile-a-compiled-pyc-file-into-a-py-file – Saeed Jul 30 '19 at 13:38
  • `dis`, as has been mentioned, produces output intended for human consumption. There are other modules that produce disassembly intended to be modified and reassembled into a function: `byteplay` is the one I'm familiar with. Note that there are several versions of this module out there, each supporting only specific Python versions, since the bytecode language tends to change fairly often. – jasonharper Jul 13 '20 at 21:56
  • @jasonharper byteplay doesn't seem to work on python 3.8. – USERNAME GOES HERE Jul 14 '20 at 09:35

0 Answers0