Python exec method


In Python, exec() is a very interesting and useful built-in function, unlike the eval() function, which can only execute the result of calculating mathematical expressions, exec() can dynamically execute complex Python code and can be very powerful.

Related course: Complete Python Programming Course & Exercises

The Python exec() Method

The Python exec() method executes the object passed. The syntax is shown below:

exec(object, globals, locals)

The passed object could be a string, an open file object, or a code object.

  • String : the string can be Python statements
  • Open file : the file is parsed until it finds EOF
  • Code object : executes code

Working with the Python exec() Method

exec() string

First is a simple little example with the following code.

i = 12
j = 13
exec("answer=i*j")
print("Answer is %s"%answer)

The output of this code is.

Answer is 156

This shows that the exec() function of the third sentence executes the Python code correctly and can give the result of the calculation to the ANSWER varia So, can we get the exec() function to execute a complex Python code, why not?

func = "def fact(n):\n\treturn 1 if n==1 else n*fact(n-1)"
exec(func)
a = fact(5)
print(a)

Here func is a string, which is a function that recursively calculates the factorial product of an integer. Since exec() only supports string and code object arguments, we want to convert the recursive function into a string, of course, in Python code format, noting line feeds and indents. The output of the preceding example is.

120

Some readers may be confused. Isn't this code directly executable in Python, so why go to the trouble of writing it as a string and executing it with exec()? The answer is that the example just now is just to demonstrate the basic use of the exec() function, which is much more powerful than that.

python exec method

exec() file

In actual projects, we sometimes write Python code into files, such as the following eg.txt, which stores the Python code we want, for example.

def fact(n):
    if n==1:
        return 1
    else:
        return n*fact(n-1)
t = fact(6)
print(t)

Again, please note that this is a Python code in txt format. So, how do we call it? The answer is the exec() function with the following code.

with open('E://eg.txt', 'r') as f:
    s = f.read()

exec(s)

In the above code, we first read the contents of the eg.txt file and then forward it to the exec() function for execution, the output is as follows.

720

Isn't that a little awesome?

exec() object

In addition to the ability to execute string and code objects, arguments can be added to the exec() function, and the passing of arguments can be written in dictionary (dict) form. Specific examples of how this is used can be found below.

x = 10

expr = """
z = 30
sum = x + y + z
print(sum)

"""

def func():
    y = 20
    exec(expr)
    exec(expr, {'x': 1, 'y': 2})
    exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4}

func()

The output is as follows.

60
33
34

In the expr statement, there are three variables x,y,z, where the value of z is given, and we can specify the value of x,y outside the exec() function, or we can specify the value of x,y in the form of a dictionary in the exec() function. In the last statement, we give the value of x,y,z, and the value of y is repeated, the exec() function receives the latter value of y, and the passing of z does not work, so the output is 34.\