Python3 exec Function
Description
exec Executes Python statements stored in a string or file; compared to eval,exec it can execute more complex Python code.
Syntax
The syntax of exec is as follows:
exec(object[, globals[, locals]])
Parameters
- object: required parameter, the Python code to be specified. It must be a string or a code object. If object is a string, it is first parsed as a set of Python statements and then executed (unless a syntax error occurs). If object is a code object, it is simply executed.
- globals: optional parameter, the global namespace (holding global variables); if provided, it must be a dictionary object.
- locals: optional parameter, the current local namespace (holding local variables); if provided, it can be any mapping object. If omitted, it takes the same value as globals.
Return Value
The return value of exec is always None.
Example
The following shows examples of using exec:
Example 1
exec
(
'
print("Hello World")
'
)
Hello
World
A single-line statement string
exec
(
"
print ('runoob.com')
"
)
runoob
.
com
A multi-line statement string
exec
(
"""
for i in range(5): ... print ("iter time: %d" % i) ...
"""
)
iter
time
:
0
iter
time
:
1
iter
time
:
2
iter
time
:
3
iter
time
:
4
Example 2
x
=
10
expr
=
"""
z = 30 sum = x + y + z print(sum)
"""
def
func
(
)
:
y
=
20
exec
(
expr
)
exec
(
expr
, {
'
x
'
:
1
,
'
y
'
:
2
}
)
exec
(
expr
, {
'
x
'
:
1
,
'
y
'
:
2
}, {
'
y
'
:
3
,
'
z
'
:
4
}
)
func
(
)
Output result:
60
33
34
The exec return value
In Python,exec The function executes code in a string but returns no value; to obtain a return value from executed code, use the eval function or exec together with locals() or globals() to read the variable's value.
Please note that using eval and exec requires care, especially when the executed code comes from an untrusted source, as there may be security risks.
** Using eval to get a return value:**
Example
code
=
'2 + 2'
result
=
eval
(
code
)
(
result
)
In this example,eval Execute the string '2 + 2' and return the result 4。
The output of the above code is:
4
Use exec with locals() to get a return value:
Example
code
=
'result = 2 + 2'
local_vars
=
{
}
exec
(
code
,
globals
(
)
,
local_vars
)
result
=
local_vars
[
'result'
]
(
result
)
In this example,exec Execute the string 'result = 2 + 2' and store the result in the local_vars dictionary under the 'result' key.
The output of the above code is:
4
Use exec with globals() to get a return value:
Example
code
=
'result = 2 + 2'
global_vars
=
{
}
exec
(
code
,
global_vars
)
result
=
global_vars
[
'result'
]
(
result
)
In this example,exec Execute the string 'result = 2 + 2' and store the result in the global_vars dictionary under the 'result' key.
The output of the above code is:
4
Python3 built-in function