Skip to content
Built-in Functions

exec()

Execute Python statements stored as text.

exec(source, globals=None, locals=None)

exec() runs Python statements from a string or code object. It is powerful, so only use trusted source text.

Parameters

NameDescription
sourceA string or compiled code object containing Python statements.
globalsOptional dictionary that supplies global names.
localsOptional mapping that supplies local names.

Returns

None; executed code may change a namespace.

Try it

Run it and change it
code = "message = 'done'"
scope = {}
exec(code, scope)
print(scope["message"])

Worth knowing

  • Only execute text you trust.

Related entries