You are currently viewing exec() Function In Python – Detailed Guide With Code

exec() Function In Python – Detailed Guide With Code

The exec() function in Python allows us to execute the block of Python code from a string. This built-in function in Python can come in handy when we need to run the dynamically generated Python code but it is recommended not to use it carelessly due to some security risks that come with it.

In this tutorial, we’ll be going to learn

  • how to work with Python’s exec() function
  • how to execute Python code using the exec() function with code examples
  • executing Python code from a string and Python source file
  • using globals and locals parameters

Python’s exec() function

Python’s exec() function allows us to execute any piece of Python code no matter how big or small that code is. This function helps us to execute the dynamically generated code.

Think of a Python interpreter that takes the piece of code, processes it internally, and executes it, the exec() function does the same. It is like an independent Python interpreter.

The exec() is capable of executing simple Python programs as well as fully featured Python programs. It can execute function calls and definitions, class definitions and instantiations, imports, and much more.

Syntax

exec(object [ , globals [ , locals]])

  • object – It must be a string or a code object. If it is a string, it is parsed as a suite of Python statements which is executed unless a syntax error occurs. If it is a code object then it will simply execute.
  • globals and locals – This allows us to provide dictionaries representing the global and local namespaces.

Return value

The return value of the exec() function is None. It may be because every piece of code doesn’t have the final result.

Initial glance

Here’s an initial look at the working of the exec() function.

Another example of using the exec() function

It works exactly like a Python interpreter, taking our code, processing it internally, executing it, and returning the correct results.

We’re running an infinite loop, and inside it, we’re taking input from the command line and wrapping it in the exec() function to execute it.

Executing code from a string input

We can use the exec() function to execute the code which is in a string format. There are multiple ways that we can use to build the string-based input:

  • Using one-liners code
  • Using new line characters
  • Using triple-quoted strings with proper formatting

Using one-liner string-based input

In Python, single-line code, also known as one-liner code, is code written in a single line that can perform multiple tasks at the same time.

If we wrote a single line of Python code, it would look like this:

Output

But if we run the above code using the exec(), the code would be

The other code we wrote above will return nothing if we execute it, instead, the output will be stored in the code variable for later access.

Executing multiple lines of code separated by new line characters

We can combine multiple statements in a single-line string using the new line characters \n.

Output

A new line character (\n) is defined to make the exec() function understand our single-line string-based code as a multiline set of Python statements.

Using triple-quoted string

In Python, we frequently use triple quotes to comment on or document our code. However, in this case, we’ll use it to generate string-based input that looks and behaves exactly like normal Python code.

The code we write within triple quotes must be properly indented and formatted, just like normal Python code. See the example below for a better understanding.

Output

The above code is similar to standard Python code, with proper indentation and formatting, but it is wrapped within triple quotes, resulting in string-based input stored in the sample_code variable, which was then executed using the exec() function.

Executing code from a Python file

We can use the exec() function to execute the code from Python(.py) source file by reading the content of the file using the open() function.

Consider the following example, which includes a sample.py file containing the following code:

The code simply prints the anime’s name here, while the following block of code takes the input of your favorite anime separated by commas and prints the desired output.

Executing the Python source file using the exec function

Output

We used the open() function using the with statement to open the .py file as a regular text file and then used the .read() on the file object to read the content of the file as a string into the file variable which is passed in the exec to execute the code.

Using globals and locals params

These parameters are entirely optional. We can use globals and locals parameters to limit the use of functions, methods, and variables that aren’t required.

Because these parameters are optional, omitting them causes the exec() function to execute the input code in the current scope. Consider the following example to better understand it.

Output

The code above ran successfully and produced an output that combined both global variables. Because the globals and locals parameters were not specified, the exec() function executed the code input in the current scope. The current scope is global in this case.

Here’s an example of how to get the value of a variable in the current scope of code.

In the preceding code, we attempted to access the value of the out variable before calling exec() and received an error.

However, we can access the value of the out variable after calling exec() because the variable defined in the code input will be available in the current scope after calling exec().

Output

Using globals and locals parameters

Output

The code returns an error because we didn’t define the key holding the str2 in the dictionary, so the exec() doesn’t have access to it.

Output

The exec() function now has access to both global variables, and the code returns the output without error, but we didn’t have access to the out after the call to exec() this time because we’re using the custom dictionary to provide an execution scope to the exec().

Here’s an example of using locals and globals together

Output

In the above code, we called exec() from within the local function. In the global scope, we have global variables and a local variable in the local scope (function level). The globals parameter specifies the variables str1 and str2, while the locals parameter specifies the variable x.

Blocking unnecessary methods and variables

Using the globals and locals params, we can control whether to restrict or use any variable or method in our code input. In this section, we’ll limit some of the functions in Python’s datetime module.

Output

We restricted the use of the datetime method from the datetime module, which resulted in an error.

Using necessary methods and variables

We can only use the methods that are required with the exec().

Output

The error occurred because the date method was not permitted. Except for two methods, datetime and timedelta, all methods in the datetime module were forbidden.

Let’s see what else we can accomplish with globals and locals parameters.

Output

Inside the exec() function, only the slice() method and all built-in methods can be executed. Even though the slice() method is not from the datetime module, it works perfectly here.

We can also limit the use of __builtins__ by setting it to None.

Output

We limited the use of __builtins__, so we can’t use the built-in methods and can only execute the printsumslice, and dir methods inside the exec().

Conclusion

We’ve learned how to use the built-in Python exec() function to execute code from a string-based input. It allows you to run dynamically generated Python code.

The topics we’ve learned

  • what is exec() function and working with it
  • executing Python code from a string-based input and Python source files
  • understanding the use of the globals and locals parameters

Additionally, we’ve coded some of the examples which helped us understand the exec() function better.


πŸ†Other articles you might be interested in if you liked this one

βœ…How to use assert statements to debug the code in Python?

βœ…Upload and display images on the frontend using Flask in Python.

βœ…Building a Flask image recognition webapp using a deep learning model.

βœ…What is generator and yield keyword in Python?

βœ…Public, Protected, and Private access modifiers in Python.

βœ…How to build a CLI command in a few steps using argparse in Python?

βœ…How to perform high-level file operations using shutil module in Python?

βœ…How to scrape a webpage’s content using BeautifulSoup in Python?


That’s all for now

Keep Coding✌✌