Updated April 11, 2023
Introduction to exec Python
exec() is an inbuilt function or a method in python that enables dynamic execution of the raw code or open file object or code object given within the exec statement. The raw code is parsed, interpreted for errors as python code, and gets executed instantly, the file is also parsed till its last line and executed and the code object is executed as it is. The exec has two optional arguments in its format that allow global variables and local variables to control its execution. Though the effect of execution will be seen instantly, this method does not pass on any value to the other parts of the program.
Syntax of exec Python
Given below is the syntax mentioned:
exec(object, dictionary : global variables, dictionary : local variables)
1. Object
It can be a string, file, or code object.
- String: It is the code text provided in the exec statement. If this code is correct syntactically then it is converted as a temporary executable and gets executed instantly.
- File: All the lines from the file are parsed and executed similar to the code explained above.
- Code object: It is executed as provided.
2. Global Variables
These are the global parameters that has presence/control over the entire program. These global parameters restrict the execution of the code within the boundary values defined in Exec statement. These global variables are independent of any functions and are used globally anywhere in the program. It is only optional and default action will result in full access to all methods. Python enables users to pass on only the select methods the program need to access to and these lists of method can be passed as dictionary elements.
3. Local Variables
Local parameters have a presence within the function and it controls the operation of that function only. These local variables are defined within a function and the scope is restricted within the function. Developers can mention the list of methods the function can have access to and the list is given in the form of a dictionary. It is only optional and the default action will provide full access to all the methods in the called module.
How exec works in Python?
Given below shows how exec works in Python with examples:
a. Exec independent of global and local parameters
Here there are no global or local parameters defined to restrict access for the program or functions. The program works within the scope available.
Code 1: Simple code
# Sample code is run in the exec method
exec("print(' . ')")
exec("print('Welcome to First Exec program')")
Output:
Code 2: To compute a cube of 6
# Sample code is run in the exec method
exec("print(' . ')")
exec("print('Cube of 6 is ')")
exec("print(6**3)")
Output:
Code 3: To call a function within exec
import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
n = input("number ")
n=int(n)
print (" ")
exec("print ('square root of ',n, ' is ', square_root(n))")
Output:
b. The exec with global parameters
Code 1: Simple program without global parameters
from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))")
Output:
Code 2: No permission
The same program gets into error with no permission to execute any of the global module. The null ‘{}’ option in the global option stops permission to all excepting built-in functions.
from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{})
Output:
Code 3: With permission given for sqrt this program runs successfully
from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{"sqrt":sqrt})
Output:
Code 4: With global permission given for factorial only, this program that calls sqrt fails
from math import * # importing Mathematics module
exec ("print('Square Root of a number')")
exec("print (sqrt(64))",{"factorial":factorial})
Output:
Code 5: Dictionary listings without global parameters
The entire directory access is listed.
from numpy import * #importing numpy module
exec ("print (dir())")
Output:
And ………….. so on…
Code 6: Dictionary listings with global parameters
from numpy import * # importing Mathematics module
exec ("print (dir())",{})
Output:
Access to builtins dictionary is only allowed.
Within builtin function also specific controls can be applied like {“__builtins__” : None}
c. Exec with local parameters
If local parameters are not provided in the Exec statement, by default, all builtin parameters will be used as local parameters, but its scope will be limited within the function.
Code 1: Without global and local parameters works fine
import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))")
Output:
Code 2: With nil permission to global and local parameters it fails
import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))",{},{})
Output:
Code 3: With nil permission for global and limited permission for local it works fine
import math # importing Mathematics module
def square_root(l): # Function beginning
return math.sqrt(l) # Returning results
exec("print ('square root of 64 is ', square_root(64))",{__builtins__:None}, {"square_root":square_root})
Output:
Permissions can be granted for local parameters and the scope can be restricted accordingly. Global and local parameters can be adjusted as per the requirements and exec function can be used to a great extent.
Conclusion
The exec is slightly risky if the program allows free option to user to choose their own code and execute. User may use them indiscreetly and eat away all the resources and cause performance glitch. Sometime it may lead to a system crash. Hence developers will have to be judicious in throwing this exec option to users to execute whatever they opt for.
Recommended Articles
This is a guide to exec Python. Here we discuss the introduction and how exec works in python with examples respectively. You may also have a look at the following articles to learn more –