Tutorial Study Image

Python exec()

This built-in function helps to execute the programs which are dynamically created. The exec() function receives a string or block of code for execution. And it is parsed and executed as a python statement.


exec(object, globals, locals) #Where object can be a string or a code object
 

Security risks

If we using a Unix system (macOS, Linux, etc) and import an OS module, it helps to provide OS functionalities like read, write of a file. And a user input a value using exec(input()) it may issue commands to change file or even delete all the files using the command os.system('rm -rf *').

exec() Parameters:

Takes 3 parameters where a first parameter is an object and if the object is a string it executed as a python statement and if it is an open file then it is executed until EOF, and if it is a code object then it is simply exected.

Parameter Description Required / Optional
object Either a string or a code object Required
globals A dictionary containing global variables. Optional
locals A dictionary containing local variables. Optional

exec() Return Value

It doesn't return any value. It just executes the given string or code object.

Examples of exec() method in Python

Example 1: Simple execution example


x = 1

exec('print(x==1)')

exec('print(x+2)') 
 

Output:

True
3

Example 2:Python exec() dynamic code execution example


from math import *

for l in range(1, 3):

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

Output:

Enter Code Snippet to execute:
print(sqrt(16))
4.0
Enter Code Snippet to execute:
print(min(2,1))
1
Done

Example 3:Passing empty dictionary as globals parameter


from math import *
exec('print(dir())', {})

# This code will raise an exception
# exec('print(sqrt(9))', {})
 

Output:

['__builtins__']

Example 4:Passing both globals and locals dictionary


from math import *

globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
exec('print(dir())', globalsParameter, localsParameter)
 

Output:

['dir', 'print']