exec, eval to execute [python] statement

exec 2. Built-in functions

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.

How to use

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

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.

Summary

Executing a python statement with exec Single expression evaluation with eval

Recommended Posts

exec, eval to execute [python] statement
Python exec statement
Python eval can execute statements.
Python --Difference between exec and eval
[Introduction to Udemy Python3 + Application] 33. if statement
Python if statement
Updated to Python 2.7.9
[Python] if statement
Python assert statement
"Backport" to python 2
To execute a Python enumerate function in JavaScript
[Introduction to Udemy Python3 + Application] 40.while else statement
[Introduction to Udemy Python3 + Application] 43. for else statement
Execute Power Query by passing arguments to Python
[Python] Summary of eval / exec functions + How to write character strings with line breaks
Python basics ② for statement
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Rewrite Python2 code to Python3 (2to3)
Automatically execute python file
How to install python
python decorator to retry
Introduction to Python language
Execute command from Python
Introduction to OpenCV (python)-(2)
Execute python3 system with PHP exec () on AWS EC2
Note to daemonize python
Introducing Python 2.7 to CentOS 6.6
Specifies the function to execute when the python program ends
Execute Python function from Powershell (how to pass arguments)
[Introduction to Udemy Python3 + Application] 68. Import statement and AS
Connect python to mysql
[Python MinMaxScaler] Normalize to 0 ~ 1
How to execute a command using subprocess in Python
Execute command from python
Python basic if statement
[Python] for statement error
[Introduction to Udemy Python3 + Application] 42. for statement, break statement, and continue statement
[Introduction to Udemy Python3 + Application] 39. while statement, continue statement and break statement
[Python] How to write an if statement in one sentence.
How to define multiple variables in a python for statement
[Road to intermediate Python] Use if statement in list comprehension
I didn't know how to use the [python] for statement
Building an environment to execute python programs on AWS EC2
How to execute external shell scripts and commands in python
Connect to BigQuery with Python
[2020.8 latest] How to install Python
[python] Convert date to string
Post from Python to Slack
How to install Python [Windows]
Post to vim → Python → Slack
Introduction to Python Django (2) Win
To flush stdout in Python
Convert numpy int64 to python int
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
Cheating from PHP to Python
A road to intermediate Python
Try to understand Python self
Python notes to forget soon
[Python] How to use list 1