I keep hearing that the eval() function is unsafe. It is a nice function, because you can use it like
print eval("2.5*49.7/(23+3.14)")
and it will solve the math.

Is there any way to protect against some nasty minded person to enter a "os.system(command)" where the command will erase a file or all files?

Recommended Answers

All 2 Replies

Several languages offer the eval() function and its safety is hotly debated. You hear eval() is only one letter away from evil()!

My feelings, if eval() is directly connected to a user input, avoid it!!! This is particularly true for Python's input() function that uses raw_input() and then sends the string to eval() to extract the number. In this case you can't even intercept the input, so if a nasty person enters (don't even try this!!!) "__import__('os').system('del *.*')" you just wiped out all the files on your drive!

If you use raw_input(), then you could check the input string for 'os' or 'system' before sending it to the eval() function. A safe use of eval() would be in a GUI calculator, where the input is limited by the buttons you have supplied.

I will avoid using the input() function then. How would you write a custom numeric_input function using raw_input()?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.