exec() Syntax The syntax
for exec() is: exec(object, global, local) exec() Parameters The exec() method
takes three parameters
: object –
- A global string or code
- optional) – a mapping object (commonly dictionary
object (optional) – a local dictionary (
) exec() Return value The exec() method returns no value. Example 1: Python exec()
program = ‘a = 5\nb=10\nprint(“Sum =”, a+b)’ exec(program)
Output sum
= 15 In the
previous example, we passed the string object program to the
exec() method.
The method executes the python code inside the object method and produces the output Sum = 15.
Example 2: exec() with a single-line program input # get a complete program as input program = input(‘Enter a program:’) # run the
exec
(program) program
Output
Enter a program: [print(item) for item in [1, 2, 3]] 1 2 3
In the example above, we provided the
code; print(item) for item in [1, 2, 3]
as
the input value. Here, we have used the exec() method
to execute the program object that has the user input code
.
Note: When using the exec() method with the OS module, you have to be careful. This is because you may accidentally change and delete files when you use the os.system(‘rm -rf*’) code in the entry.
Example 3: exec() with a multiline input program
We can pass a multiline 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’) # run the program exec(b)
Output
Enter a program:’a = 5\nb=10\nprint(“Sum =”, a+b)’ 90
In the example above, we passed a multiline program as an argument to the exec() method.
But before that, We need to compile this program using the compile() method.
Example 4: Checking usable code
with exec()
It’s a good idea to check the methods and variables you can use with the exec() method. You can do this with the help of dir() method.
# import all methods from math library from math import * # check usable methods exec(‘print(dir())’)
Output
[‘In’, ‘Out’, ‘_’, ‘__’, ‘___’, ‘__builtin__’, ‘__builtins__’, ‘__name__’, ….] Example 5: Blocking unnecessary methods and variables 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, see locals() and globals().
# import methods from math library from math import * # use cbrt() method mycode=”’a = cbrt(9) print(a)”’ # empty dictionary (global parameter) to constrain the cbrt() method exec(mycode, {})
Output
NameError: name ‘cbrt’ is not defined
In the previous example, we restricted the use of the cbrt() method in exec() even though we imported the entire math library.
That’s why we get the output NameError: name ‘cbrt’ is not defined.
Example 6: Using
Required Methods and Variables in exec() We can also make the
necessary methods and variables available for use with the
exec() method.
To do this, we need to pass the local 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’]
In the example above, we have blocked all built-in global methods
with 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 the 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 we want to access.
Recommended reading
Python
- compile
- Python dir()
()