How do you set up a stack?

kosh kosh at aesaeion.com
Wed May 9 04:37:00 EDT 2001


s713221 at student.gu.edu.au wrote:

> kosh wrote:
>> 
>> Umm. While this solution will work I think there are some things that
>> need to be dealt with. Mainly you need to check f for items that should
>> not be in there. eval will evaulatuate any valid piece of python code so
>> the other things that can be done are large. This is a fairly large
>> security risk at this point I think. At the very least I would check if
>> it has any letter characters and if so not run then.
> 
> Eval will (should?) only evaluate legal pythonic numeric functions. This
> actually covers quite a bit, but unless you define wierd class
> structures that overwrite numerical operators to do non-numerical
> operations, you shouldn't have to worry too much about using eval.
> 

Eval can evaluate any python expression by default. The other stuff you 
tried were statements and as such they would need exec. I have some complex 
thing being done with eval in places that are not numeric at all. However 
it is checked thoroughly.

> Simple maths.
>>>> eval("1+2")
> 3
> 
> Math with complex numbers (Except "i" is replaced with "j" in python.
> Ask the engineers why. *sighs*)
>>>> eval("(1+2j)-3j")
> (1-1j)
> 
> You can also import the math module and use these functions inside the
> eval statement.
>>>> import math
>>>> eval("1+math.sqrt(2)")
> 2.4142135623730949
> 
> However, all of these are dealing with numbers. I'd be interested to see
> if someone did have an example of a malicious eval use. (In fact I'd be
> downright anxious to know of any eval security weaknesses. *grins*)
> 
> I try to eval a non-numerical statement.
>>>> eval("print 'hello'")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 1
>     print 'hello'
>         ^
> SyntaxError: invalid syntax
> 
> Now I try a different statement that barfs on a different piece of
> syntax.
>>>> eval("if 1==1: print 'hello'")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 1
>     if 1==1: print 'hello'
>      ^
> SyntaxError: invalid syntax
>>>>
> 
> In order to "evaluate" or execute a string as a command, rather than an
> expression, the exec command has to be used. However, if you are really
> paranoid, or would like to convert the following complex number
> statements "1+32i" to correct python, "1+32j", look up the re module.
> 
> Anycase, have fun. You should have a great time with the language, and
> with this newsgroup.
> 
> Joal Heagney/AncientHart
> 




More information about the Python-list mailing list