Python exec() with Examples

FREE Online Courses: Click, Learn, Succeed, Start Now!

We are going to discuss another built-in function in Python. This is Python exec(), which is a short form for execution. This article will learn this function, its parameters, and also its limitations with examples. So let us start.

Introduction to Python exec() function

As said above, the function exec() is a built-in function in Python. It takes either a string or an object as the first and necessary parameter for the dynamic execution of the input.

If a string is given as an input, then it is parsed as a suite of Python code. After this, it is executed if there are no syntax errors. If an object is passed, then it is directly executed.

Syntax of python exec()

exec(object, globals=None, locals=None)

The first argument is a must, and the two are optional and hold a default value None. The following points describe the three arguments :

1. object: It is either a string or an object to be executed

2. globals: This is a dictionary that contains the global methods and variables

3. locals: This is a dictionary or a mapped object with the local methods and variables

This function does not return any value or result of execution. The output is None.

Lets us see an example of the exec() function.

Example of Python exec() function:

exec('name="PythonGeeks"\nprint("Name:",name)')

Output:

Name: PythonGeeks

In this example, we could give more than one line of code as an input for the function to execute.

Other Examples of Python exec() Function

We can also give multiline inputs using triple quoted strings. For example,

Example of exec() function with multiline input:

exec("""a=6
b=5
print('a*b: ',a*b)""")

Output:

a*b: 30

In this example, we first created two variables, and then we printed their product

We can give loops, conditionals, and user-defined functions. For example,

Example of exec() with for loop and conditional as input string:

exec("""for i in range(5):
  if(i%2==0):
    print(i)
""")

Output:

0
2
4

Example of exec() with a function as input:

exec("""def func():
  print('Welcome to PythonGeeks')
func()""")

Output:

Welcome to PythonGeeks

We can also take a code as an input from the user and use it in the exec() function as shown in the below example.

Example of exec() with user input:

code=input('Enter a program: ')

exec(code)

Output:

Enter a program: for i in ‘Python’:print(i)

P
y
t
h
o
n

Difference between exec() and eval()

If anyone knew both the exec() and eval() function, the first question that person would get is ‘What is the difference between them?’. To be honest, it happened to me too. So, let us list some differences between these two functions.

1. Return value:

The function eval() returns the result of the input expression as the output. But the function exec() does not return an input. For example, see that on running the below codes, the eval() gives output but the exec() does not.

Example of the difference between exec() and eval() regarding the return value:

eval('4*5+3/3')

Output:

21.0

Example of the difference between exec() and eval() regarding the return value:

exec('4*5+3/3')

We do not get output here.

2. The difference in the input string:

The eval() function can take only one expression. Also, it cannot take the code with loops, conditionals, and statements that include compilation like assignment of variable

But in the above section, we saw that the exec() function can take more than one expression, which includes loops, conditionals, and assignment statements.

The below code shows the example of getting an error on using these with the eval(), but getting output with the exec().

Example of the difference between exec() and eval() regarding the input:

eval('a=5\nprint("a:",a)')

exec('a=5\nprint("a:",a)')

Output:

Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
eval(‘a=5\nprint(“a:”,a)’)
File “<string>”, line 1
a=5
^
SyntaxError: invalid syntax
a: 5

Example of the difference between exec() and eval() regarding the input:

eval('for i in range(5): print(i)')

exec('for i in range(5): print(i)')

Output:

Traceback (most recent call last):
File “<pyshell#16>”, line 1, in <module>
eval(‘for i in range(5): print(i)’)
File “<string>”, line 1
for i in range(5): print(i)
^
SyntaxError: invalid syntax
0
1
2
3
4

Problem with the exec() function

The exec() function can execute any piece of code we give as input. This might include accessing confidential details or modifying other files that should not be allowed to be accessed.

1. Issue with the exec() function

Assume that you have imported the os module. Using the exec() function, the user can give the commands as an input to change the path/ delete files. For more understanding see the below code:

Example of the problem of Python exec():

import os

code=input('Enter a program: ')

exec(code)

Output:

Enter a program: print(os.listdir())

[‘DLLs’, ‘Doc’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘NEWS.txt’, ‘python.exe’, ‘python3.dll’, ‘python39.dll’, ‘pythonw.exe’, ‘Scripts’, ‘tcl’, ‘Tools’, ‘vcruntime140.dll’, ‘vcruntime140_1.dll’]

Using the above input, one can view all the files in the os. There are more worse possibilities of modifying the path. The below code shows how one can do these.

Example of changing path using the exec():

code=input('Enter a program: ')

exec(code)

Output:

Enter a program: os.chdir(‘C:\\Users’)

The below code shows the way to delete the files from a directory.
Example of deleting files using the exec():

code=input('Enter a program: ')

exec(code)

Output:

Enter a program: os.system(‘rm -rf *’)

2. Solving the problem of exploitation

It is important to restrict the exec() function to only those methods and directories that we do want the user to access to make the program secure. This can be done by checking the variables and methods available in the directory using the dir() function.

Look at the below code to view the methods and objects in the directory in an empty idle.

Example of checking dir() of empty idle:

dir()

Output:

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]

Let us see what happens when we create an object or a function and when we import a module.

Example of checking dir() on creating objects:

var=5
def func(a):
    print(a**2)

dir()

Output:

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘func’, ‘var’]

We can see that on creating objects, the names of these objects get added to the directory.

Example of checking dir() on importing modules:

from math import *

dir()

Output:

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__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’, ‘func’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘isqrt’, ‘lcm’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘nextafter’, ‘perm’, ‘pi’, ‘pow’, ‘prod’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’, ‘ulp’, ‘var’]

In this example, we can observe that on importing the math module, the functions and constants of the module got added to the directory.

Exec() globals and locals parameters

We saw above that the dir() holds all the objects of the program, which also includes that of the imported modules. We can restrict the exec() function to some of these functions using the optional arguments, globals, and locals.

When a second argument is passed to the exec() function, by default it is considered to be the global parameter.

Let us see an example of passing an empty dictionary and checking the methods that exec() can access using the dir() function.

Example of using empty dictionary as global argument:

exec('print(dir())',{})

Output:

[‘__builtins__’]

We can see that exec() can access only the built in functions on passing an empty dictionary as global argument.

When we pass the empty dictionary as the global, the other functions from other modules do not work. Let us see the difference without the global argument and with {} as the global argument.

Example of exec() with no global argument:

from math import *

exec('print(sin(0))')

Output:

0.0

Now let us see what will happen when we give an empty dictionary as the global.

Example of exec() with {} as global argument:

from math import *

exec('print(sin(0))',{})

Output:

Traceback (most recent call last):
File “<pyshell#26>”, line 1, in <module>
exec(‘print(sin(0))’,{})
File “<string>”, line 1, in <module>
NameError: name ‘sin’ is not defined

We can use the global argument to restrict the exec() to certain functions of the module. In addition, we can also change the name of the function, For example,

Example of restricting exec() to some functions of the module:

from math import *

exec('print(power(4,0.5))',{'power':pow})

Output:

2.0

We can pass both global and local parameters to the exec() function. For example,

Example of passing both global and local parameters:

from math import *

exec('print(ceil(5.4))',{'builtins': __builtins__},{'ceil':ceil})

Output:

6

We can also pass only the local argument too. As we discussed, the global dominates the local parameter. So, we need to set it to None as shown in the below example.

Example of passing local parameter:

from math import *

exec('print(floor(5.4))',{'builtins': None},{'floor':floor})

Output:

5

Interview Questions on Python exec()

1. Write a program to initiate a variable and execute the expression x**3+4==2*x+5. And print the result.

Ans. Below is the example of Python exec():

exec('x=5\nprint(x**3+4==2*x+5)')

Output:

False

2. Write a program to check if the number is positive or not.

Ans. Below is the example of exec() with multiline code:

exec('''n=4
if (n>0):
  print("Number is positive")
else:
  print("Number is not positive")''')

Output:

Number is positive

Q3. Write a program to take an input of a number from the user and write a program to print the first 5 multiples of the number.

Ans. Below is the example of Python exec() with input:

n=int(input('Enter a number: '))

exec('for i in range(1,6): print(n*i)')

Output:

3
6
9
12
15

Q4. Write a program to pass only the cos() function from the math module along with the built-in functions and print the values in the directory.

Ans. Below is the example of exec() with global values:

exec('print(dir())',{'cos':cos})

Output:

[‘__builtins__’, ‘cos’]

Q5. Write a program to restrict the global methods of the eval() to only print(), abs(). Print the directory and print the value of the absolute value of -4

Ans. We can do this by setting the global built-in functions as None and setting the print() and abs() functions as locals.

Example of restricting exec() to certain built-in functions:

exec('print(dir())',{'builtins': None},{'print':print,'abs':abs})

exec('print(abs(-4))',{'builtins': None},{'print':print,'abs':abs})

Output:

[‘abs’, ‘print’]

4

Quiz on Python Exec() FUnction

Conclusion

In this article, we learned the exec() function, the difference between exec() and eval(), and the problem with exec(). Then we saw the different cases of local and global parameters. And at the end, we practiced some coding questions.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


2 Responses

  1. Yves says:

    clean and clear explanations with valuable examples,
    Thanks

  2. Yves says:

    It seems that question 3 is ill posed:
    “Which of the following is not correct about the exec() function”
    please check

Leave a Reply

Your email address will not be published. Required fields are marked *