Python's eval is a built-in function, the role of this function is to return the result of the expression string passed. Imagine variable assignment, the expression on the right of the equal sign written in the format string, the string as an argument to eval, eval return value is the result of this expression.
Usage in python eval function is very flexible, but also very dangerous, safety is its biggest drawback. This article from both the flexibility and the risk of introduction eval.
1, the power of
A few examples feel transformed string list, tuple, dict's.
Powerful bar, to a string to eval, eval expressions give you a return value.
eval The syntax is as follows:
expression: String
globals: variable scope, global namespace, if provided, must be a dictionary object.
locals: variable scope, the local name space, if provided, may be any map object.
Combined with globals and locals look at a few examples
Globals transmitted parameter value { "age": 1822},
Output
Coupled with the locals variables
The above two examples can be seen that when the parameter is blank locals, globals parameter is not empty, to find whether there is a variable parameter globals, and is calculated.
When the two parameters are not empty, look locals first parameter, and then find the parameter globals, locals parameter of the same name will overwrite the globals variables in the variable.
2. The danger
eval is convenient, but be aware that security can be converted into a string expression and execution, you can use to perform system commands to delete files and other operations.
Assume that a malicious user input. such as:
eval("__import__('os').system('ls /home/pythontab.com/www/')")
So after eval (), you will find that the current folder files are now in front of the exhibition user. In fact, this sentence is equivalent to the implementation of the
os.system('ls /home/pythontab.com/www/')
Then continue typing:
eval("__import__('os').system('cat /home/pythontab.com/www/test.sql')")
Posters of the code.
Again a delete command, the file disappeared. such as
eval("__import__('os').system('rm /home/pythontab.com/www/test.data')")
So use eval, on the one hand to enjoy his flexibility, we must also pay attention to safety.