How to execute a python code from a string

How to execute a python code from a string:

In python, we can execute a code from a string. It means the code or program is written as a string and it is assigned to a string variable, the python program will execute the program from the string variable.

Where to use it?

One thing that comes to our mind is where to use it. Normally we might not need to execute a code from a string, the code will be written in python files and the interpreter will execute it directly.

Alternative way to solve this problem:

But, sometimes, we might need to execute a piece of code dynamically. For example, we have one server running on python, and we want to execute a piece of code that the server gets it on API requests. To execute that, we can either create one file, write the code in it and execute that code from the file. But writing a file is expensive. Also, we need to remove that file after the execution is done. Again, if the server is receiving thousands of request parallely, we need to create thousands of files.

We can avoid creating new files as python already provides one method called exec().

In this post, we will learn how to use exec() method with examples.

Example program to use exec:

Let’s take a look at the below program:

code_str = '''
print('Multiplying two numbers :')

first_num = 20
second_num = 30

print(first_num * second_num)
'''

exec(code_str)

Here,

  • code_str is a multiline string. This string actually holds a python program.
  • Using exec, we are executing this python program.

If you run this program, it will give the below output:

Multiplying two numbers :
600

python exec example

Exception:

exec can throw an error if the code it is running has any issue. It works similar to any other python program. If your python program has any issue, it will throw an error and it will quit.

Why you should avoid running any unknown code:

exec is a powerful method. It can run anything as a python program. If you are getting this value from user, like an API call, someone might use any dangerous code snippet like deleting all files in your server, mine bitcoin etc. So, if you are not sure about the input, it is a good idea to avoid running exec on any code that you get.

You might also like: