Michael Chermside mcherm at
Thu Jul 17 20:14:05 CEST 2003

Chris Wright wants a way to execute python code one-line-at-a-time so he
can run multiple functions "in lockstep".

I don't have an answer, but I have the START of an approach. Michael Sparks
is ahead of me here (see his excellent answer, but
for a different approach try this:

ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on
Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     print '1-1'
...     print '1-2'
...     print '1-3'
>>> import dis
>>> dis.dis(f.func_code)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_CONST               1 ('1-1')
          9 PRINT_ITEM
         10 PRINT_NEWLINE

         11 SET_LINENO               3
         14 LOAD_CONST               2 ('1-2')
         17 PRINT_ITEM
         18 PRINT_NEWLINE

         19 SET_LINENO               4
         22 LOAD_CONST               3 ('1-3')
         25 PRINT_ITEM
         26 PRINT_NEWLINE
         27 LOAD_CONST               0 (None)
         30 RETURN_VALUE

Here we can SEE the code, and it's nicely broken into lines by
the SET_LINENO bytecode. What I'd LIKE to do now is to somehow
go from f.func_code (a code object) to a Python list of bytecodes.
Then we could easily split the list on SET_LINENO codes, intersperse
with calls to other functions, and sew it all up into a larger
list. Then we would just need to exec those bytecodes, and BINGO...
problem solved.

But I don't know how to convert a code object into a list of
bytecodes, nor how to convert it back to a code object so I can
pass it to exec.

Any better gurus able to enlighten me?

-- Michael Chermside

More information about the Python-list mailing list