How do I parse a Python script?

Earlier today, I asked a question about how Python handles certain types of loops. One of the answers contained disassembled versions of my examples.

I would like to know more. How can I parse native Python code?

+10


a source to share


3 answers


Look at the dis module :



def myfunc(alist):
    return len(alist)

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_FAST                0 (alist)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE

      

+12


a source


Use a module dis

from the Python standard library ( import dis

for example, in an interactive interpreter, then dis.dis

any function you care about!).



+2


a source


Besides being used dis

as a module, you can also run it as a command line tool

For example, on windows, you can run:

c:\Python25\Lib\dis.py test.py

      

And it will output the disassembled result to the console.

+2


a source







All Articles