How to Use the Python exec() Function

09/12/2021

Contents

In this article, you will learn how to use the Python exec() function.

Python exec() Function

The exec() function in Python is used to dynamically execute code specified as a string or a code object. It can be useful for a number of purposes, such as dynamically generating code, implementing eval()-like functionality, or executing code from external sources with unknown or untrusted content.

Syntax
exec(object, globals=None, locals=None)
Parameters
  • object: A string of Python code, or a code object that you want to execute.
  • globals (optional): A dictionary of global variables that will be available in the context of the executed code. If not specified, the current global namespace will be used.
  • locals (optional): A dictionary of local variables that will be available in the context of the executed code. If not specified, the current local namespace will be used.
Example

Here’s an example of how to use exec() to execute a string of Python code:

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

# Output
# Hello, World!

Note that exec() can be dangerous if you’re executing code from untrusted sources, as it allows for full access to the runtime environment, including any imported modules and libraries, so you should be careful when using it and make sure to validate the source of the code before executing it.