Python's exec() function is used to dynamically execute Python code. It accepts a string containing Python code as a parameter and executes it as a Python program.

Function Syntax

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

Parameters:

  • object: Can be a string containing Python code, a code object, or an open file object.
  • globals and locals: Optional parameters for specifying global and local namespaces during code execution.

The code executed by exec() has full permissions and can access and modify all Python objects and namespaces, so special care must be taken when using exec() to avoid security issues.

For namespace and security considerations, refer to:

The exec() function dynamically compiles and executes the specified Python code. If the object parameter is a string, exec() parses it as a set of Python statements and compiles it into executable bytecode; then it executes these statements in the specified namespace. If object is a code object, exec() directly executes the code represented by that object. If object is a file object, exec() reads code from the file and executes it.

exec() Function Examples

Execute Python code from a string:

code = "print('Hello, World!')"
exec(code)

Execute Python code represented by a code object:

code_obj = compile("print('Hello, World!')", "<string>", "exec")
exec(code_obj)

Read Python code from a file and execute it:

with open("test.py") as f:
    code = f.read()
exec(code)