The exec() method executes a dynamically created program, which is either a string or a code object.
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: 10Example 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 globalsExample 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.
program = input('Enter a program:')
b = compile(program, 'something', 'exec')
exec(b)output
Enter a program:'a = 5\nb=10\nprint("Sum =", a+b)'
90Example 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:
from math import *
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.
from math import *
mycode='''a = cbrt(9)
print(a)'''
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 definedObserve 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 *
globalsParameter = {'__builtins__' : None}
localsParameter = {'print': print, 'dir': dir}
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.