Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
exec() in Python
The exec() function in Python allows you to dynamically execute Python code at runtime. It can execute code passed as a string or compiled code object, making it useful for scenarios where code needs to be generated and executed programmatically.
Syntax
exec(object, globals, locals)
Where:
object − A string containing Python code or a compiled code object
globals − Optional dictionary defining the global namespace (default: current globals)
locals − Optional dictionary defining the local namespace (default: current locals)
Basic String Execution
The simplest use case is executing a string containing Python code ?
x = 9
exec('print(5 * x)')
45
Executing Multi-line Code
You can execute code blocks with multiple statements using proper newlines and indentation ?
code_block = '''
x = 3
if x < 5:
print(x * x)
else:
print("x is too large")
'''
exec(code_block)
9
Using Global Parameters for Security
By default, exec() has access to all imported modules and functions. You can restrict this by passing an empty dictionary as the globals parameter ?
import math
# Without restrictions - has access to math module
exec("print(dir())")
print("---")
# With empty globals - only built-ins available
exec("print(dir())", {})
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math'] --- ['__builtins__']
Allowing Selected Functions
You can provide controlled access by specifying only certain functions in the globals dictionary ?
import math
# Allow only specific functions
safe_globals = {
"sqrt": math.sqrt,
"pi": math.pi,
"print": print
}
exec("print('Square root of pi:', sqrt(pi))", safe_globals)
Square root of pi: 1.7724538509055159
Using Local Parameters
The locals parameter controls the local namespace. You can combine it with restricted globals for fine-grained control ?
import time
# Restrict both global and local scope
restricted_globals = {"__builtins__": None}
allowed_locals = {
"current_time": time.time,
"print": print
}
exec("print('Current timestamp:', current_time())", restricted_globals, allowed_locals)
Current timestamp: 1703123456.789
Security Considerations
| Usage | Security Level | Recommended For |
|---|---|---|
exec(code) |
Low | Trusted code only |
exec(code, {}) |
Medium | Restricted environment |
exec(code, {}, locals) |
High | Sandboxed execution |
Conclusion
The exec() function is powerful for dynamic code execution but requires careful consideration of security implications. Always restrict the global and local namespaces when executing untrusted code to prevent potential security vulnerabilities.
