Python exec() function:
The Python exec() function is a built-in function that supports the dynamic execution of Python code. However, the parameter must be either a string or a code object. If it is a string, it executes as Python statements if and only if there are no syntax errors. In the case of an Object, it simply executes.
Signature
The signature for the exec() method is as shown below. It takes three parameters.
exec(object, globals, locals)
Parameters and return type
- Here, The exec() method takes one mandatory and two optional parameters. An object is a string or object that contains executable code. The globals and locals are optional parameters that specify dictionary and mapping objects.
- However, it doesn’t return anything.
Python Built-in Function exec Examples:
Example 1: In this example, we take a string and execute it as Python code using the exec() function. As a result, it will print Python programming.
code = 'print("Welcome to the world of Programming")'
exec(code)
Output
Welcome to the world of Programming
Example 2: In this example, We will demonstrate the working of the exec function along with a compile function. Firstly, let us take a file test.py
that contains the code shown below.
s="Python Programming"
print(s)
We will read the file content as a string and then compile it to a code object. After that, exec()
function executes this code object.
# reading code from a file
f = open('test.py', 'r')
x = f.read()
f.close()
code = compile(x, 'test.py', 'exec')
exec(code)
Output
Python Programming
Example 3: We will provide a global parameter to the exec() function in this example. As we can see, values for the variables in this dictionary is used for execution. So, it fetches the value of variable a and computes the square of a, resulting in value 25.
# Initializing
code="print(a*a)\nprint('Python Programming')"
# Initializing globals
globals={'a':5}
# Using exec
exec(code,globals)
Output
25
Python Programming
Conclusion
The exec() function is used to dynamically execute python code from an object which can be a file or string. This method works with the compile method.
References
Happy Learning 🙂