Last Updated : 10 Jan, 2025
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 functionexec() 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.
Python
code = "x = 5\ny = 10\nprint(x + y)"
exec(code)
Explanation:
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.
Python
code = "5 + 10"
res = eval(code)
print(res)
Explanation:
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.
Python
code = "x = 5\ny = 10\nprint(x + y)"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)
Explanation:
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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4