Open In App

Execute a String of Code in Python

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Sometimes, we encounter situations where a Python program needs to dynamically execute code stored as a string. We will explore different ways to execute these strings safely and efficiently.

Using the exec function

exec() function allows us to execute dynamically generated Python code stored in a string. It is the most straightforward and commonly used method for this purpose.

code = "x = 5\ny = 10\nprint(x + y)"
exec(code)

Output
15

Explanation:

  • exec() function takes the string of code as an argument and executes it as Python code.
  • variables x and y are created and their sum is printed.
  • This method is simple and works well for executing multiple lines of code stored as a string.

Let’s explore some more methods and see how we can execute a string of code in Python.

Using eval()

eval() function can execute a single expression stored in a string and return its result. It is more limited compared to exec() but can be useful for evaluating expressions.

code = "5 + 10"
res = eval(code)
print(res)

Output
15

Explanation:

  • eva() function evaluates the string as a Python expression and returns the result.
  • This method is ideal for scenarios where we only need to execute and get the result of a single expression.

Using compile()

compile() function can be used to compile a string of code into a code object, which can then be executed using exec() or eval(). This is useful for advanced use cases where we need more control.

code = "x = 5\ny = 10\nprint(x + y)"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)

Output
15

Explanation:

  • compile() function converts the string of code into a code object.
  • exec() function is then used to execute the compiled code object.
  • This method is useful for scenarios where we need to compile the code once and execute it multiple times.

Using subprocess module

If we want to execute the code in a separate process, we can use the subprocess module. This is more suitable for executing standalone scripts or commands.

import subprocess

code = "print(5 + 10)"
subprocess.run(["python3", "-c", code])

Output
15

Explanation:

  • The subprocess.run function is used to execute the string of code as a separate Python process.
  • The -c flag allows us to pass the code string directly to the Python interpreter.
  • This method is useful when we need isolation or want to execute the code in a separate environment.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg