Execute a String of Code in Python
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.
code = "x = 5\ny = 10\nprint(x + y)"
exec(code)
Output
15
Explanation:
- exec(code) executes the string code as Python code.
- Variables x and y are created, and their sum is printed.
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
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.
code = "x = 5\ny = 10\nprint(x + y)"
res = compile(code, '<string>', 'exec')
exec(res)
Output
15
Explanation:
- compile(code, '<string>', 'exec') compiles the string into a code object.
- exec(compiled_code) executes the compiled code.
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:
- subprocess.run([...]) runs a separate Python process.
- -c flag allows passing code directly as a string.