Bu Kodu Nasıl Metine Çevirebilirim?

Merhaba.

Fonksiyonlarla uğraşırken, şu kod:

def f1(b): print("f1 çalıştı.")

print(f1.__code__.co_code)

Bana şunu döndürdü:

b't\x00d\x01\x83\x01\x01\x00d\x00S\x00'

Bunu nasıl okunabilir(sayı veya metin) hale getirebilirim?

>>> def f1(b): print("f1 çalıştı.")

>>> from dis import dis
>>> dis(f1)
  1           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('f1 çalıştı.')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
>>> 
1 Beğeni

f1.__code__.co_code ile dönen byte verisi aslında içeriklerin byte değerleri.

import dis


def f1(): print("hello")


x = f1.__code__.co_code
print(x)

for instr in dis.Bytecode(f1):
    print(dis.opmap[instr.opname].to_bytes(1, byteorder="little"))

Karşılaştırın isterseniz:

b't\x00d\x01\x83\x01\x01\x00d\x00S\x00'
b't'
b'd'
b'\x83'
b'\x01'
b'd'
b'S'
1 Beğeni

Hmm…, peki bu bytecode'lar, benim ne işime yarayabilir?
Yani bunlar aslında birer Assembly kodu mu oluyor?

Hayır, bytecode ile machine code ayrı şeyler.

The main difference between the machine code and the bytecode is that the machine code is a set of instructions in machine language or binary which can be directly executed by the CPU. While the bytecode is a non-runnable code generated by compiling a source code that relies on an interpreter to get executed.

difference between bytecode and machine code
difference between bytecode and assembly code

1 Beğeni

Hmm… teşekkür ederim.

Python (CPython?) sanal makinesinin assembly kodu, evet.