Parsing variables out of python lines

Mark Hobbes2176 at yahoo.com
Mon Oct 7 07:43:54 CEST 2002


I hate finding answer quickly after posting.  Anyway, here is code that will
solve my problem:


import tokenize
import StringIO

foo = [1,2,3]
x = "for i in foo:"

#
#The StringIO trick turns a string into a read'able object (or so it seems)
#
t = tokenize.generate_tokens(StringIO.StringIO(x).readline)

for junk, item, rest1, rest2, rest3 in t:
    if item in vars():
        print eval(item),
    else:
        print item,
print

With output:
==> for i in [1, 2, 3] :

Anyone know how to clean up the tuple assignment (I only want item, the rest 
could go to /dev/null if they want).

Thanks anyways.  Hope this is useful for someone else.

Regards,
Mark



More information about the Python-list mailing list