AppDividend
Latest Code Tutorials

Python exec() Function Example

0

Python exec() function executes the dynamically created program, which is either a string or a code object. If it is object code, it executed merely, but if it is a string, then the string is parsed as the suite of Python statement, which is then executed; otherwise, a syntax error occurs.

Python exec()

Python exec() method executes the dynamically created program, which is either a string or a code object. See the following syntax.

Syntax

exec(object, globals, locals)

object: Here object is either a string or a code object.

globals: This can be a dictionary, and the parameter is optional.

locals: This can be a mapping object, and this is an optional field.

Python exec() function does not return anything.

How exec() works with an example

See the following code.

# Program to display working of exec()
prog = "a=10 \nb=5 \nprint('Sum of two is: ',a+b)"

# calling exec()
exec(prog)

Output

➜  pyt python3 app.py
Sum of two is:  15
➜  pyt

Here, a string object prog is passed to exec(), and it executes.

Passing global and locals dictionary

See the following code.

# app.py

# Passing global variable only
from math import *
# Only the global variable is passed
exec("print(dir())", {})

Output

➜  pyt python3 app.py
['__builtins__']
➜  pyt

Here, in this example, we can see that we are passing an empty dictionary as a parameter to exec() function, and only the __builtin__ is displayed, and no other math functions are displayed. Because the global parameter overtakes the local parameter as it is empty.

But we can pass global and local parameters together in a simple statement. Let’s look at the example below.

See the following code.

# app.py

# Passing global and local variable variable
from math import *
# Only the global and local both are passed
exec("print(dir())", {'print': print, 'sum': sum})

Output

➜  pyt python3 app.py
['__builtins__', 'print', 'sum']
➜  pyt

So we can see that, using local parameters, we can implement our function according to our needs. Here,  print, sum all are printed.

Also, we can restrict the use of the __builtin__ method like the following.

# app.py

# Restricting gobal variable
from math import *
# we are giving restrictio to __builtin__
exec("print(dir())", {"__builtins__": None}, {
     "sum": sum, "print": print, "dir": dir})

Output

➜  pyt python3 app.py
['dir', 'print', 'sum']
➜  pyt

So here, we can see that only dir, print, and sum are displayed.

Cautions while using exec()

Consider the situation, you are using a Unix system (macOS, Linux, etc.) and you have imported os module.

The os module provides a portable way to use operating system functionalities like read or write a file.

If you allow users to input value using exec(input()), the user may issue commands to change files or even delete all the files using the command.

os.system('rm -rf *')

If you are using the exec(input()) in your code, it’s a good idea to check which variables and methods the users can use.

You can see which variables and methods are available using dir() method.

More often than not, all the available methods and variables used in exec() may not be needed, or even may have the security hole.

You can restrict the use of these variables and methods bypassing the optional globals and locals parameters (dictionaries) to the exec() method.

Python exec() dynamic code execution

Let’s look at another example where the user will enter the code to be executed by our program.

See the following code.

# app.py

from math import *

for l in range(1, 4):

    func = input("Enter Code to execute:\n")
    try:
        exec(func)
    except Exception as ex:
        print(ex)
        break
print('Home Run')

Output

➜  pyt python3 app.py
Enter Code to execute:
print(sqrt(81))
9.0
Enter Code to execute:
print(max(19,21))
21
Enter Code to execute:
print(min(11,21))
11
Home Run
➜  pyt

Finally, Python exec() Function Example is over.

Related Posts

Python setattr()

Python print()

Python repr()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.