how to determine an 'open' string?

Bernhard Herzog bh at intevation.de
Thu May 16 14:43:30 EDT 2002


Skip Montanaro <skip at pobox.com> writes:

>     holger> with my replacement rlcompleter module i'd like to
>     holger> have a *correct* check if a string is 'open'.
> 
> How about just trying to eval() the string?  Assuming it begins with a
> quotation mark or apostrophe it should be safe to call eval(). 

If you mean the builtin eval without any form of restricted execution,
you're not safe. Consider

s = """'', eval(<evilcode>)"""
eval(s)

Where <evil code> can do practically anything! 

If you chose <evil code> carefully, the code might do anything. E.g.:

>>> s = """'', eval(compile("import os; os.system('ls')", "", "single"))"""
>>> eval(s)
build	       configure.in  Lib	      Misc	pyconfig.h.in
buildno        CVS	     libpython2.1.a   Modules	python
config.cache   Demo	     LICENSE	      Objects	Python
config.h       Doc	     Mac	      Parser	README
config.log     Grammar	     Makefile	      PC	RISCOS
config.status  Include	     Makefile.pre     PCbuild	setup.py
configure      install-sh    Makefile.pre.in  PLAN.txt	Tools
0
('', None)
>>> 

Better:

>>> myglobals = {"__builtins__":{}}
>>> eval(s, myglobals, {})
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 0, in ?
NameError: name 'eval' is not defined
>>> 

But then you don't know whether the string contains correct quotes...

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list