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
| Name | Description |
|---|---|
| source | A string or compiled code object containing Python statements. |
| globals | Optional dictionary that supplies global names. |
| locals | Optional 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.