Analysis of exec and eval usage of python

  • 2020-06-15 09:37:13
  • OfStack

Introduction to the

python dynamically executes string snippets (or files), usually using exec,eval.

exec


exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]

Note: exec is a syntax declaration, not a function.

The official document explains exec


This statement supports dynamic execution of Python code.

The first expression of exec could be:

1. Code string
2. File objects
3. Code objects
4.tuple

The first three are pretty much the same, but the fourth is a little bit more special and I'll do it at the end

If you ignore the following optional expressions, the code following exec executes in the current field


>>> a=2
>>> exec "a=1"
>>> a
>>> 

If you use the in option to specify 1 dic after the expression, it will be scoped as the global and local variables


>>> a=10
>>> b=20
>>> g={'a':6,'b':8}
>>> exec "global a;print a,b" in g
>>>

If two expressions are specified after in, they will be used as global and local variable scopes, respectively


>>> a=10
>>> b=20
>>> c=20
>>> g={'a':6,'b':8}
>>> l={'b':9,'c':10}
>>> exec "global a;print a,b,c" in g,l
>>>

Now the case of tuple, which is why many people mistakenly think of exec as a function.

If the first expression is tuple


exec(expr, globals) # It equivalent to  exec expr in globals
exec(expr, globals, locals) # It equivalent to  exec expr in globals,locals

eval

eval is typically used to execute 1 string expression and return the value of the expression.


eval(expression[, globals[, locals]])

There are three arguments, the expression string, the globals variable scope, and the locals variable scope. The second and third parameters are optional.

If the next two arguments are ignored, eval executes in the current scope.


>>> a=1
>>> eval("a+1")
>>>

If the globals parameter is specified


>>> a=1
>>> g={'a':10}
>>> eval("a+1",g)
>>>

If the locals parameter is specified


>>> a=10
>>> b=20
>>> c=20
>>> g={'a':6,'b':8}
>>> l={'b':9,'c':10}
>>> eval("a+b+c",g,l)
>>>

If you want to strictly limit the implementation of eval, set globals to ___, and this expression can only be accessed by ___, 86en__ module.

conclusion

exec,eval gives me great flexibility, but it also carries the hidden danger that we should always remember to specify the scope of their execution when using them.

The above is about exec python exec, eval use analysis of the entire content, I hope to help you. Those who are interested can continue to see this site:

Analysis of potential risk code from eval

Python verifies that files are read-write code sharing

The Python file operates on basic process code instances

If there is any deficiency, please let me know. Thank you for your support!


Related articles: