Python exec() Function
The exec()
method executes a dynamically created program, which is either a string or a code object.
The exec()
function accepts large blocks of code, unlike the eval()
function which only accepts a single expression
Syntax
exec(object, globals, locals)
exec() Parameters
Python exec()
function parameters:
Parameter | Condition | Description |
---|---|---|
object | Required | A String, or a code object |
globals | Optional | A dictionary containing global parameters |
locals | Optional | A dictionary containing local parameters |
exec() Return Value
Python exec()
function does not return any value.
Examples
Example 1: executing a simple print statement
exec('print("Hello, World!")')
Example 2: defining a variable within the exec() context
exec('a = 5')
Example 3: accessing a variable defined outside the exec() context
a = 10
exec('print(a)') # Output: 10
Example 4: using globals and locals to control the execution context of exec()
global_vars = {"x": 10, "y": 20}
local_vars = {"x": 5}
exec("print(x)", global_vars, local_vars) # Output: 5, because locals takes precedence over globals
Example 5: exec() with a multi-line input program
We can pass a multi-line input program to the exec()
method with the help of \n
. But we need to use the compile()
method to compile the program first.
# get a multi-line program as input
program = input('Enter a program:')
# compile the program in execution mode
b = compile(program, 'something', 'exec')
# execute the program
exec(b)
output
Enter a program:'a = 5\nb=10\nprint("Sum =", a+b)'
90
Example 6: check usable code with exec()
It is a good thing to verify the methods and variables that can be utilized with the exec()
function.
You can accomplish this by employing the dir()
function, which lists all the attributes and methods of an object
For example:
# import all the methods from math library
from math import *
# check the usable methods
exec('print(dir())')
output
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Example 7: block not necessary methods and variable in exec()
Most of the time, we don't need all the methods and variables with exec()
.
We can block these unnecessary methods and variables by passing the optional globals
and locals
parameter to the exec()
method.
For more information, check locals()
function and globals()
function.
# import methods from the math library
from math import *
# use cbrt() method
mycode='''a = cbrt(9)
print(a)'''
# empty dictionary (global parameter) to restrict the cbrt() method
exec(mycode, {})
output
Traceback (most recent call last):
File "main.py", line 9, in <module>
exec(mycode, {})
File "<string>", line 1, in <module>
NameError: name 'cbrt' is not defined
Observe that in this example we have restricted the use of the cbrt()
method in exec()
although we have imported the whole math
library.
Example 8: using necessary methods and variables in exec()
You can also make the necessary methods and variables available to use with the exec()
method.
To do this, we need to pass the locals dictionary to exec()
.
from math import *
# set globals parameter to none
globalsParameter = {'__builtins__' : None}
# set locals parameter to take only print() and dir()
localsParameter = {'print': print, 'dir': dir}
# print the accessible method directory
exec('print(dir())', globalsParameter, localsParameter)
output
['dir', 'print']
Notice that we have blocked all the global builtin methods with the code:
globalsParameter = {'__builtins__' : None}
but, we have allowed two methods print()
and dir()
to be executable with the code:
localsParameter = {'print': print, 'dir': dir}
Finally, we have passed the dir()
method inside print()
method and then passed it to the exec()
method to print a list of usable methods.
The globalsParameter
and localsParameter
here are optional parameters that we have used with the exec()
method to print only the methods that we want to access.