This article mainly introduces the exec and eval usage examples in Python. This article summarizes the exec and eval functions in Python in a concise way and provides examples, if you need it, you can use exec to execute dynamic Python code, similar to Javascript's eval function. The eval function in Python can calculate the Python expression and return the result (exec does not return the result, print (eval ("... ") Print None );
The code is as follows:
>>> Exec ("print (\" hello, world \")")
Hello, world
>>> A = 1
>>> Exec ("a = 2 ")
>>>
2
There is a scope (namespace, scope) concept here. in order not to break the current scope, you can create a scope (a dictionary) to execute exec (Javascript does not have this function ):
The code is as follows:
>>> Scope = {}
>>> Exec ("a = 4", scope)
>>>
2
>>> Scope ['A']
4
>>> Scope. keys ()
Dict_keys (['A', '_ builtins _'])
_ Builtins _ contains all built-in functions and values;
The common {} does not contain _ builtins __
The code is as follows:
>>> A = {}
>>> A. keys ()
Dict_keys ([])
Like exec, eval can also use the namespace:
The code is as follows:
>>> Result = eval ('2 + 3 ')
>>> Result
5
>>> Scope = {}
>>> Scope ['A'] = 3
>>> Scope ['B'] = 4
>>> Result = eval ('a + B ', scope)
>>> Result
7