Python3 exec Function
Description
execExecutes Python statements stored in a string or file. Compared toeval,execit can execute more complex Python code.
Syntax
The following is the syntax for exec:
exec(object[, globals[, locals]])
Parameters
- object: Required parameter, representing the Python code to be specified. It must be a string or a code object. If object is a string, the string is first parsed into 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, representing the global namespace (stores global variables). If provided, it must be a dictionary object.
- locals: Optional parameter, representing the current local namespace (stores local variables). If provided, it can be any mapping object. If this parameter is ignored, it will take the same value as globals.
Return Value
The return value of exec is always None.
Examples
The following shows examples of using exec:
Example 1
Example 2
Output:
60 33 34
exec Return Value
In Python,execthe function is used to execute code in a string, but it does not return any value. If you want to get the return value after executing the code, you can useevalfunction orexeccombined withlocals()orglobals()to get the value of the variable.
Please note that usingevalandexecrequires caution, especially when the executed code comes from an untrusted source, as there may be security risks.
Useevalto get the return value:
Example
result = eval(code)
print(result)
In this example,evalexecutes the string'2 + 2'and returns the result4。
The output of the above code execution is:
4
Usingexeccombined withlocals()to get the return value:
Example
local_vars = {}
exec(code, globals(), local_vars)
result = local_vars['result']
print(result)
In this example,execexecutes the string'result = 2 + 2', and stores the result inlocal_varsin the dictionary's'result'key.
The output of the above code execution is:
4
Usingexeccombined withglobals()to get the return value:
Example
global_vars = {}
exec(code, global_vars)
result = global_vars['result']
print(result)
In this example,execexecutes the string'result = 2 + 2', and stores the result inglobal_varsin the dictionary's'result'key.
The output of the above code execution is:
4Other Extensions
Python3 Built-in Functions