{"id":873,"date":"2022-10-16T16:14:00","date_gmt":"2022-10-16T10:44:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=873"},"modified":"2023-08-15T16:18:41","modified_gmt":"2023-08-15T10:48:41","slug":"exec-function-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/exec-function-in-python","title":{"rendered":"exec() Function In Python &#8211; Detailed Guide With Code"},"content":{"rendered":"\n<p>The&nbsp;<code>exec()<\/code>&nbsp;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&nbsp;<strong>dynamically generated Python code<\/strong>&nbsp;but it is recommended not to use it carelessly due to some security risks that come with it.<\/p>\n\n\n\n<p>In this tutorial, we&#8217;ll be going to learn<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>how to work with Python&#8217;s&nbsp;<code>exec()<\/code>&nbsp;function<\/li>\n\n\n\n<li>how to execute Python code using the&nbsp;<code>exec()<\/code>&nbsp;function with code examples<\/li>\n\n\n\n<li>executing Python code from a string and Python source file<\/li>\n\n\n\n<li>using&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters<\/li>\n<\/ul>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-pythons-exec-function\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-pythons-exec-function\"><\/a>Python&#8217;s exec() function<\/h1>\n\n\n\n<p>Python&#8217;s&nbsp;<code>exec()<\/code>&nbsp;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&nbsp;<strong>dynamically generated code<\/strong>.<\/p>\n\n\n\n<p>Think of a Python interpreter that takes the piece of code, processes it internally, and executes it, the&nbsp;<code>exec()<\/code>&nbsp;function does the same. It is like an independent Python interpreter.<\/p>\n\n\n\n<p>The&nbsp;<code>exec()<\/code>&nbsp;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-syntax\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-syntax\"><\/a>Syntax<\/h3>\n\n\n\n<p><code>exec(object [ , globals [ , locals]])<\/code><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>object<\/code>&nbsp;&#8211; It must be a&nbsp;<strong>string<\/strong>&nbsp;or a&nbsp;<strong>code object<\/strong>. If it is a string, it is parsed as&nbsp;<em>a suite of Python statements<\/em>&nbsp;which is executed unless a syntax error occurs. If it is a code object then it will simply execute.<\/li>\n\n\n\n<li><code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;&#8211; This allows us to provide dictionaries representing the global and local namespaces.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-return-value\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-return-value\"><\/a>Return value<\/h3>\n\n\n\n<p>The return value of the&nbsp;<strong><em>exec()<\/em><\/strong>&nbsp;function is&nbsp;<strong>None<\/strong>. It may be because every piece of code doesn&#8217;t have the final result.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-initial-glance\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-initial-glance\"><\/a>Initial glance<\/h3>\n\n\n\n<p>Here&#8217;s an initial look at the working of the&nbsp;<code>exec()<\/code>&nbsp;function.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">obj = [\"apple\", \"cherry\", \"melon\", \"strawberry\"]\ncode = \"print([sliced[:4] for sliced in obj if 'a' not in sliced])\"\n\nexec(code)\n\n.........\n['cher', 'melo']<\/pre><\/div>\n\n\n\n<p>Another example of using the&nbsp;<code>exec()<\/code>&nbsp;function<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># The code will continuously run and we can run our code as we do in \n# Python interpreter \nwhile True:\n    exec(input(\"&gt;&gt;&gt; \"))<\/pre><\/div>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">&gt;&gt;&gt; print(\"Welcome to GeekPython\")\nWelcome to GeekPython\n\n&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; print(np.random.randint(16, size=(2, 4)))\n[[11 13  3 13]\n [ 7  6 15  5]]\n\n&gt;&gt;&gt; x = [\"apple\", \"banana\", \"cherry\", \"mango\"]\n&gt;&gt;&gt; print([fruit for fruit in x if \"a\" not in fruit])\n['cherry']<\/pre><\/div>\n\n\n\n<p>It works exactly like a Python interpreter, taking our code, processing it internally, executing it, and returning the correct results.<\/p>\n\n\n\n<p>We&#8217;re running an infinite loop, and inside it, we&#8217;re taking input from the command line and wrapping it in the&nbsp;<code>exec()<\/code>&nbsp;function to execute it.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-executing-code-from-a-string-input\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-executing-code-from-a-string-input\"><\/a>Executing code from a string input<\/h1>\n\n\n\n<p>We can use the&nbsp;<code>exec()<\/code>&nbsp;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:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using one-liners code<\/strong><\/li>\n\n\n\n<li><strong>Using new line characters<\/strong><\/li>\n\n\n\n<li><strong>Using triple-quoted strings with proper formatting<\/strong><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-using-one-liner-string-based-input\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-using-one-liner-string-based-input\"><\/a>Using one-liner string-based input<\/h3>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>If we wrote a single line of Python code, it would look like this:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">obj = [\"apple\", \"cherry\", \"melon\", \"strawberry\"]\n\nprint([sliced[:4] for sliced in obj if 'a' not in sliced])<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">['cher', 'melo']<\/pre><\/div>\n\n\n\n<p>But if we run the above code using the&nbsp;<code>exec()<\/code>, the code would be<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">obj = [\"apple\", \"cherry\", \"melon\", \"strawberry\"]\n\nexec(\"print([sliced[:4] for sliced in obj if 'a' not in sliced])\")\n#-----------------------------OR--------------------------------\nexec(\"code = [sliced[:4] for sliced in obj if 'a' not in sliced]\")<\/pre><\/div>\n\n\n\n<p>The other code we wrote above will return nothing if we execute it, instead, the output will be stored in the&nbsp;<code>code<\/code>&nbsp;variable for later access.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-executing-multiple-lines-of-code-separated-by-new-line-characters\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-executing-multiple-lines-of-code-separated-by-new-line-characters\"><\/a>Executing multiple lines of code separated by new line characters<\/h3>\n\n\n\n<p>We can combine multiple statements in a single-line string using the new line characters&nbsp;<code>\\n<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">exec(\"square = int(input('Enter the number: '))\\nprint(f'The square of {square}:', square**2)\")<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Enter the number: 30\nThe square of 30: 900<\/pre><\/div>\n\n\n\n<p>A new line character (<code>\\n<\/code>) is defined to make the&nbsp;<code>exec()<\/code>&nbsp;function understand our single-line string-based code as a multiline set of Python statements.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-using-triple-quoted-string\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-using-triple-quoted-string\"><\/a>Using triple-quoted string<\/h3>\n\n\n\n<p>In Python, we frequently use triple quotes to comment on or document our code. However, in this case, we&#8217;ll use it to generate string-based input that looks and behaves exactly like normal Python code.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">sample_code = \"\"\"\n\nintegers = [4, 7, 2, 9, 44]\n\ndef square(num):\n    return num ** 2\n\ndef odd_num(num):\n    return num % 2 == 1\n\nsquare_if_even = [square(number) for number in integers if number % 2 == 0]\n\nodd_number = [number for number in integers if odd_num(number)]\n\nprint(\"Original values:\", integers)\n\nprint(\"Square of even number:\", square_if_even)\n\nprint(\"Odd number:\", odd_number)\n\n\"\"\"\nexec(sample_code)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Original values: [4, 7, 2, 9, 44]\nSquare of even number: [16, 4, 1936]\nOdd number: [7, 9]<\/pre><\/div>\n\n\n\n<p>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&nbsp;<code>sample_code<\/code>&nbsp;variable, which was then executed using the&nbsp;<code>exec()<\/code>&nbsp;function.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-executing-code-from-a-python-file\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-executing-code-from-a-python-file\"><\/a>Executing code from a Python file<\/h1>\n\n\n\n<p>We can use the&nbsp;<code>exec()<\/code>&nbsp;function to execute the code from Python(<code>.py<\/code>) source file by reading the content of the file using the&nbsp;<a target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/functions.html#open\" rel=\"noreferrer noopener\">open()<\/a>&nbsp;function.<\/p>\n\n\n\n<p>Consider the following example, which includes a&nbsp;<code>sample.py<\/code>&nbsp;file containing the following code:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"sample.py\"># sample.py\ndef anime(name):\n    print(f\"Favourite anime: {name}\")\n\nanime(\"One Piece\")\n\nlist_of_anime = input(\"Enter your favourite anime: \").split(\",\")\nprint(\"Your Favourite anime:\", list_of_anime)<\/pre><\/div>\n\n\n\n<p>The code simply prints the anime&#8217;s name here, while the following block of code takes the input of your favorite anime separated by commas and prints the desired output.<\/p>\n\n\n\n<p><strong>Executing the Python source file using the exec function<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">with open(\"sample.py\", mode=\"r\") as sample:\n    file = sample.read()\n\nexec(file)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Favourite anime: One Piece\nEnter your favourite anime: One Piece, Naruto, Demon Slayer, Jujutsu kaisen\nYour Favourite anime: ['One Piece', ' Naruto', ' Demon Slayer', ' Jujutsu kaisen']<\/pre><\/div>\n\n\n\n<p>We used the&nbsp;<code>open()<\/code>&nbsp;function using the&nbsp;<code>with<\/code>&nbsp;statement to open the&nbsp;<code>.py<\/code>&nbsp;file as a regular text file and then used the&nbsp;<code>.read()<\/code>&nbsp;on the file object to read the content of the file as a string into the&nbsp;<code>file<\/code>&nbsp;variable which is passed in the&nbsp;<code>exec<\/code>&nbsp;to execute the code.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-using-globals-and-locals-params\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-using-globals-and-locals-params\"><\/a>Using globals and locals params<\/h1>\n\n\n\n<p>These parameters are entirely optional. We can use&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters to limit the use of functions, methods, and variables that aren&#8217;t required.<\/p>\n\n\n\n<p>Because these parameters are optional, omitting them causes the&nbsp;<code>exec()<\/code>&nbsp;function to execute the input code in the current scope. Consider the following example to better understand it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">code = \"\"\"\nout = str1 + str2\nprint(out)\n\"\"\"\n# global variables\nstr1 = \"Hel\"\nstr2 = \"lo\"\n\nexec(code)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello<\/pre><\/div>\n\n\n\n<p>The code above ran successfully and produced an output that combined both global variables. Because the&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters were not specified, the&nbsp;<code>exec()<\/code>&nbsp;function executed the code input in the current scope. The current scope is&nbsp;<strong>global<\/strong>&nbsp;in this case.<\/p>\n\n\n\n<p>Here&#8217;s an example of how to get the value of a variable in the current scope of code.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">code = \"\"\"\nout = str1 + str2\nprint(out)\n\"\"\"\n# global variables\nstr1 = \"Hel\"\nstr2 = \"lo\"\n\nprint(out)<\/pre><\/div>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Traceback (most recent call last):\n    .....\nNameError: name 'out' is not defined. Did you mean: 'oct'?<\/pre><\/div>\n\n\n\n<p>In the preceding code, we attempted to access the value of the&nbsp;<code>out<\/code>&nbsp;variable before calling&nbsp;<code>exec()<\/code>&nbsp;and received an error.<\/p>\n\n\n\n<p>However, we can access the value of the out variable after calling&nbsp;<code>exec()<\/code>&nbsp;because the variable defined in the code input will be available in the current scope after calling&nbsp;<code>exec()<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">exec(code)\nprint(out)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello\nHello<\/pre><\/div>\n\n\n\n<p><strong>Using<\/strong>&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">code = \"\"\"\nout = str1 + str2\nprint(out)\n\"\"\"\n# global variables\nstr1 = \"Hel\"\nstr2 = \"lo\"\n\nexec(code, {\"str1\": str1})<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Traceback (most recent call last):\n    ....\nNameError: name 'str2' is not defined. Did you mean: 'str1'?<\/pre><\/div>\n\n\n\n<p>The code returns an error because we didn&#8217;t define the key holding the&nbsp;<code>str2<\/code>&nbsp;in the dictionary, so the&nbsp;<code>exec()<\/code>&nbsp;doesn&#8217;t have access to it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">code = \"\"\"\nout = str1 + str2\nprint(out)\n\"\"\"\n# global variables\nstr1 = \"Hel\"\nstr2 = \"lo\"\n\nexec(code, {\"str1\": str1, \"str2\": str2})\n\nprint(out)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello\nTraceback (most recent call last):\n     ....\nNameError: name 'out' is not defined. Did you mean: 'oct'?<\/pre><\/div>\n\n\n\n<p>The&nbsp;<code>exec()<\/code>&nbsp;function now has access to both global variables, and the code returns the output without error, but we didn&#8217;t have access to the out after the call to&nbsp;<code>exec()<\/code>&nbsp;this time because we&#8217;re using the custom dictionary to provide an execution scope to the&nbsp;<code>exec()<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s an example of using&nbsp;<code>locals<\/code>&nbsp;and&nbsp;<code>globals<\/code>&nbsp;together<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">code = \"\"\"\nout = str1 + str2 + \" \" + x\nprint(out)\n\"\"\"\n# global variables\nstr1 = \"Hel\"\nstr2 = \"lo\"\n\ndef local():\n    # local variable\n    x = \"there\"\n    exec(code, {\"str1\": str1, \"str2\": str2}, {\"x\": x})\n\nlocal()<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hello there<\/pre><\/div>\n\n\n\n<p>In the above code, we called&nbsp;<code>exec()<\/code>&nbsp;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&nbsp;<code>str1<\/code>&nbsp;and&nbsp;<code>str2<\/code>, while the locals parameter specifies the variable&nbsp;<code>x<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-blocking-unnecessary-methods-and-variables\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-blocking-unnecessary-methods-and-variables\"><\/a>Blocking unnecessary methods and variables<\/h3>\n\n\n\n<p>Using the&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;params, we can control whether to restrict or use any variable or method in our code input. In this section, we&#8217;ll limit some of the functions in Python&#8217;s&nbsp;<code>datetime<\/code>&nbsp;module.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from datetime import *\n\ncode = \"\"\"\ncurr_time = datetime.now()\nprint(curr_time)\n\"\"\"\nexec(code, {})<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Traceback (most recent call last):\n     ....\nNameError: name 'datetime' is not defined<\/pre><\/div>\n\n\n\n<p>We restricted the use of the&nbsp;<code>datetime<\/code>&nbsp;method from the&nbsp;<code>datetime<\/code>&nbsp;module, which resulted in an error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"heading-using-necessary-methods-and-variables\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-using-necessary-methods-and-variables\"><\/a>Using necessary methods and variables<\/h3>\n\n\n\n<p>We can only use the methods that are required with the&nbsp;<code>exec()<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from datetime import *\n\n# Allowing only two methods\nallowed_param = {'datetime': datetime, 'timedelta': timedelta}\n\nexec(\"print(datetime.now())\", allowed_param)\nexec(\"print(datetime.now() + timedelta(days=2))\", allowed_param)\n\n# date() method is not allowed\nexec(\"print(date(2022, 9, 4))\", allowed_param)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">2022-10-15 18:40:44.290550\n2022-10-17 18:40:44.290550\n\nTraceback (most recent call last):\n     ....\nNameError: name 'date' is not defined<\/pre><\/div>\n\n\n\n<p>The error occurred because the&nbsp;<code>date<\/code>&nbsp;method was not permitted. Except for two methods,&nbsp;<code>datetime<\/code>&nbsp;and&nbsp;<code>timedelta<\/code>, all methods in the&nbsp;<code>datetime<\/code>&nbsp;module were forbidden.<\/p>\n\n\n\n<p>Let&#8217;s see what else we can accomplish with&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from datetime import *\n\n# Setting globals parameter to __builtins__\nglobals_param = {'__builtins__': __builtins__}\n\n# Setting locals parameter to take only print(), slice() and dir()\nlocals_param = {'print': print, 'dir': dir, 'slice': slice}\n\nexec('print(slice(2))', globals_param, locals_param)\nexec('print(dir())', globals_param, locals_param)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">slice(None, 2, None)\n['dir', 'print', 'slice']<\/pre><\/div>\n\n\n\n<p>Inside the&nbsp;<code>exec()<\/code>&nbsp;function, only the&nbsp;<code>slice()<\/code>&nbsp;method and all built-in methods can be executed. Even though the&nbsp;<code>slice()<\/code>&nbsp;method is not from the&nbsp;<code>datetime<\/code>&nbsp;module, it works perfectly here.<\/p>\n\n\n\n<p>We can also limit the use of&nbsp;<code>__builtins__<\/code>&nbsp;by setting it to&nbsp;<code>None<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">from datetime import *\n\n# Setting globals parameter to none\nglobals_param = {'__builtins__': None}\n\n# Setting locals parameter to take only print(), slice(), sum() and dir()\nlocals_param = {'print': print, 'dir': dir, 'slice': slice, 'sum': sum}\n\n# Allowed methods directory\nexec('print(dir())', globals_param, locals_param)\nexec('print(f\"Sum of numbers: {sum([4, 6, 7])}\")', globals_param, locals_param)<\/pre><\/div>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">['dir', 'print', 'slice', 'sum']\nSum of numbers: 17<\/pre><\/div>\n\n\n\n<p>We limited the use of&nbsp;<code>__builtins__<\/code>, so we can&#8217;t use the built-in methods and can only execute the&nbsp;<code>print<\/code>,&nbsp;<code>sum<\/code>,&nbsp;<code>slice<\/code>, and&nbsp;<code>dir<\/code>&nbsp;methods inside the&nbsp;<code>exec()<\/code>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/exec-function-in-python#heading-conclusion\"><\/a>Conclusion<\/h1>\n\n\n\n<p>We&#8217;ve learned how to use the built-in Python&nbsp;<code>exec()<\/code>&nbsp;function to execute code from a string-based input. It allows you to run dynamically generated Python code.<\/p>\n\n\n\n<p>The topics we&#8217;ve learned<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>what is&nbsp;<code>exec()<\/code>&nbsp;function and working with it<\/li>\n\n\n\n<li>executing Python code from a string-based input and Python source files<\/li>\n\n\n\n<li>understanding the use of the&nbsp;<code>globals<\/code>&nbsp;and&nbsp;<code>locals<\/code>&nbsp;parameters<\/li>\n<\/ul>\n\n\n\n<p>Additionally, we&#8217;ve coded some of the examples which helped us understand the&nbsp;<code>exec()<\/code>&nbsp;function better.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-assert\" rel=\"noreferrer noopener\">How to use assert statements to debug the code in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/render-images-from-flask\" rel=\"noreferrer noopener\">Upload and display images on the frontend using Flask in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/flask-app-for-image-recognition\" rel=\"noreferrer noopener\">Building a Flask image recognition webapp using a deep learning model<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-generators-with-yield-statement\" rel=\"noreferrer noopener\">What is generator and yield keyword in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/access-modifiers-in-python\" rel=\"noreferrer noopener\">Public, Protected, and Private access modifiers in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/argparse-in-python\" rel=\"noreferrer noopener\">How to build a CLI command in a few steps using argparse in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/shutil-module-in-python\" rel=\"noreferrer noopener\">How to perform high-level file operations using shutil module in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/web-scraping-in-python-using-beautifulsoup\" rel=\"noreferrer noopener\">How to scrape a webpage&#8217;s content using BeautifulSoup in Python<\/a>?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The&nbsp;exec()&nbsp;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&nbsp;dynamically generated Python code&nbsp;but it is recommended not to use it carelessly due to some security risks that come with it. In this tutorial, we&#8217;ll be [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":875,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2,41],"tags":[40,12,31],"class_list":["post-873","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-function","tag-functions","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/873","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=873"}],"version-history":[{"count":5,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/873\/revisions"}],"predecessor-version":[{"id":1354,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/873\/revisions\/1354"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/875"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=873"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=873"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=873"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}