Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 exec Function

Python3 exec Function

Python3 Built-in Functions Python3 built-in 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

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

)

print

(

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'

]

print

(

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'

]

print

(

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 Functions Python3 built-in function