Python exec()

The exec() method executes a dynamically created program, which is either a string or a code object.

Example

program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

# Output: Sum = 15

exec() Syntax

The syntax of exec() is:

exec(object, globals, locals)

exec() Parameters

The exec() method takes three parameters:

  • object - Either a string or a code object
  • globals (optional) - a dictionary
  • locals (optional) - a mapping object (commonly dictionary)

exec() Return Value

The exec() method doesn't return any value.


Example 1: Python exec()

program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)

Output

Sum = 15

In the above example, we have 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 an entire program as input
program = input('Enter a program:')

# execute the program exec(program)

Output

Enter a program: [print(item) for item in [1, 2, 3]]
1
2
3

In the above example, we have provided the code;

print(item) for item in [1, 2, 3]

as an input value.

Here, we have used the exec() method to execute the program object which has the user input code.

Note: When you use the exec() method with the OS module, you need to be careful. This is because you can accidentally change and delete files when you use the os.system('rm -rf *') code in the input.


Example 3: 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

In the above example, we have passed a multi-line 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 the dir() method.

# import all the methods from math library
from math import *

# check the usable methods exec('print(dir())')

Output

['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__name__', ….]

Example 5 : Blocking unnecessary 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() and globals().

# 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

NameError: name 'cbrt' is not defined

In the example above, we have restricted the use of the cbrt() method in exec() although we have imported the whole math library.

That's why we get the output NameError: name 'cbrt' is not defined.


Example 6: Using necessary methods and variables in exec()

We 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']

In the above example, 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.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges