Parsing strings (\n and \\)

François Pinard pinard at iro.umontreal.ca
Tue Jun 25 16:36:58 EDT 2002


[Fredrik Lundh]

> > A simple avenue is to get Python itself to evaluate the string
> > as a constant (you ensure this by removing evaluation context).
> > Something like this:
> >
> >     PARSED = eval(UNPARSED, {}, {})

> >>> UNPARSED = "__import__('os').system('echo dream on!')"
> >>> PARSED = eval(UNPARSED, {}, {})
> dream on!

:-) :-)

In practice, I always matched UNPARSE with a regexp which is convenient
for a string.  I remove evaluation context because none is needed.  The the
danger is probably limited or does not exist in my actual cases.

But it did not occur to me how fragile the above writing may be.  Yet another
good reason to avoid some Python constructs, like `eval', whenever possible.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list