Execute a String of Code in Python (original) (raw)

Last Updated : 1 Nov, 2025

Given a string containing Python code, the task is to execute it dynamically. **For example:

**Input: "x = 5\ny = 10\nprint(x + y)"
**Output: 15

Below are multiple methods to execute a string of Python code efficiently.

Using exec()

exec() function allows us to execute dynamically generated Python code stored in a string.

Python `

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

`

**Explanation:

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.

Python `

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

`

Using compile() with exec() or eval()

compile() converts a string into a code object, which can then be executed multiple times using exec() or eval(). Useful when the same code is run repeatedly.

Python `

code = "x = 5\ny = 10\nprint(x + y)" res = compile(code, '', 'exec') exec(res)

`

**Explanation:

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.

Python `

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

`

**Explanation: