Exec and eval instances in Python, pythoneval
Through exec, You can execute dynamic Python code, similar to the eval function of Javascript. The eval function in Python can calculate the Python expression and return the result (exec does not return the result, print (eval ("... ") Print None );
Copy codeThe 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 ):
Copy codeThe 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 __
Copy codeThe Code is as follows:
>>> A = {}
>>> A. keys ()
Dict_keys ([])
Like exec, eval can also use the namespace:
Copy codeThe Code is as follows:
>>> Result = eval ('2 + 3 ')
>>> Result
5
>>> Scope = {}
>>> Scope ['a'] = 3
>>> Scope ['B'] = 4
>>> Result = eval ('a + B ', scope)
>>> Result
7
How to obtain the python exec eval running result
Hfile = file ("f:/1.txt"," r ") # f:/1.txt: 1 + 1 string = hfile. readline () retStr = eval (string) print retStr
In python, how does one convert an int to the name of an existing object?
A = 2
Print eval ("a % s" %)
A is the number entered by the user.