Skip to content

[Python] How to exec() function to execute a program as string

Last Updated on 2021-04-07 by Clay

The basic function which calls "exec" is provided by Python, and that saved my life before a meeting, haha.

In order to appreciate (?) this function, I specially wrote an introduction to the way of using this function, hoping I can help you or everyone!

This is a simple tutorial for executing the dynamic code in Python.
If your have a dynamic code, it means you can change your execute processing in the program runtime.


exec()

In the processing of coding, we will inevitably encounter some situations that force is to dynamically add the programs we need to use the code, which is quite rare (at least one time I code the program for five years only)

text_01 = """print('Hello World!')"""
exec(text_01)


This is the most basic use case.
First we save the code to be execute into a string, and then throw the saved variable directly into exec()

And this is our output:

Hello World!

How is it? Is it really printed?


Of course, we can also input the parameters we need in the new code from the outside, such as:

text_02 = """
print('{} is a nice {}!')""".format('Today', 'day')
exec(text_02)


We can see that the code we are executing contains the symbol "{}", which is the word we entered later with format.

Here we fill in two spaces with "Today" and "day"

Today is a nice day!

We will output sentences like this.


Of course, not just the string (str), the number (int) is of course also operative.

text_03 = """
a = {}
b = {}
print(a+b)""".format(1, 5)
exec(text_03)


Output:

6

Not only we can execute that, but also we can call a function if we define it outside:

def sumOf(a, b):
    return a+b


text_04 = """
a = {}
b = {}
print(sumOf(a, b))""".format(1, 5)
exec(text_04)


Output:

6

But sometimes, maybe we will not find the function we call.

like this error:

This time, maybe we must to import the script the function it existed.

from exec_example import sumOf


With this line, we can call the function we just wrote.

exec_example is the name of my Python file, you have to change it in yours.


Finally, I will mention how to extract the "variable" from the dynamically added code part.

def sumOf(a, b):
    return a+b

text_05 = """
from exec_example import sumOf
a = {}
b = {}
total = sumOf(a, b)
""".format(7, 8)

Vars = {}
exec(text_05, Vars)
print(Vars['total'])


We define a dictionary variable "Vars" externally and then enter it into the exec() function.

after executing our dynamic code, we can use the form Vars['total'] to see the value of total in the dynamic code.

15

So the above is brief explanation of the exec() function in Python.

I hope it can help people.


References

Tags:

Leave a Reply