exec(object[, globals[, locals]]) This function supports dynamic execution of Python code. object must be a string or code object. If it is a string, the string is parsed as a series of Python statements and executed (unless a syntax error occurs). If the optional part is omitted, the code will run within its current scope.
So, here, I put a character string in object and use it.
eval
eval(expression, globals=None, locals=None) It takes a string and the optional arguments globals and locals. If you give globals, it must be a dictionary. If you give locals, it can be any mapping object. The expression argument is parsed and evaluated as a Python expression (technically a list of conditions). The dictionaries globals and locals are then used as global and local namespaces, respectively.
sample_exec.py
Python 3.5.0
>>> exec("a = 10; b = 13; print(a, b)")
10 13
>>> print(a, b)
10 13
>>> eval(`a + b`)
23
Here, exec is executing ʻa = 10, b = 13, print (a, b) . eval executes ʻa + b
and returns its value.
Also, globals () is a dictionary, so if you give a dictionary as an argument, it will write to it.
use_dict.py
Python 3.5.0
>>> a = dict()
>>> exec("b = 1; c = 2", globals(), a)
>>> a
{'b': 1, 'c': 2}
>>> eval("b + c", a)
3
In exec, the a in the empty dict is {'b': 1,'c': 2}
.
In eval, globals is a, and the value in the dictionary a is calculated. So, in reality, we are calculating ʻa ['b'] + a ['c']`.
Use this to try using it like'json.loads'.
json_like.py
# exec
''' write file '''
a = [1,2,3,4,5,6]
b = [2,3,4,5,6,7]
with open('test.txt', 'w') as fout:
fout.write('num_list_a = ' + repr(a))
fout.write('num_list_b = ' + repr(b))
''' load file '''
exec(open('test.txt').read())
print('a =', num_list_a, '\nb =', num_list_b)
# eval
''' write file '''
a = [1,2,3,4,5]
with open('test2.txt', 'w') as fout:
fout.write(repr(a))
del a
''' load file'''
num_list_c = eval(open('test2.txt').read())
print('c =', num_list_c)
output.txt
a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4, 5, 6, 7]
c = [1, 2, 3, 4, 5]
exec doesn't return a value, so you have to define the variable as a string. If you use eval, it will return a value, so if it is simple, you can use it like json.
Executing a python statement with exec Single expression evaluation with eval
Recommended Posts