Python exec() function

Example

Execute code block:

x = 'name = "Bill"\nprint(name)'
exec(x)

Running example

Definition and usage

The exec() function executes the specified Python code.

The exec() function accepts a large amount of code blocks, which is different from the eval() function that only accepts a single expression.

Syntax

exec(object, globals, locals)

Parameter value

Parameter Description
object String or code object.
globals Optional. A dictionary containing global arguments.
locals Optional. A dictionary containing local arguments.