Python3 exec Function

Python3 内置函数Python3 Built-in Functions


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

>>>exec('print("Hello World")') Hello World # Single-line statement string >>> exec("print ('example.com')") example.com # 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:

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

code = '2 + 2'
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

code = 'result = 2 + 2'
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

code = 'result = 2 + 2'
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:

4

Python3 内置函数Python3 Built-in Functions

Other Extensions