Hi Pythonistas!,
In the previous post, we discussed how to generate dynamic Python code using the exec() function.
While powerful, exec() can be dangerous if not handled properly, especially when running untrusted code.
Today, we’ll explore a safer alternative: RestrictedPython.
RestrictedPython is a sandboxing library that lets you safely execute
Python code with tight control over what that code can do.
it protects your system from:
- Accessing files
- Running system commands
- Using dangerous built-ins like open(), exec(), or eval()
Why Use It
Let’s say you want to allow users to run custom Python snippets in your app, like:
for i in range(3):
print(i*2)
Block code like this
import os
os.remove("important_file.txt")
Normal exec() is unsafe.
RestrictedPython only allows "safe" operations.
How to Use It
pip install RestrictedPython
Basic Example
from RestrictedPython import compile_restricted
from RestrictedPython import safe_globals
source_code = """
def example():
return 'Hello World!'
"""
loc = {}
byte_code = compile_restricted(source_code, '<inline>', 'exec')
exec(byte_code, safe_globals, loc)
loc['example']()
Output
Hello World!
This is a safe, limited environment:
- No import allowed
- No file or OS access
- No exec() or eval() inside the code
If we run a code like this
from RestrictedPython import compile_restricted
from RestrictedPython import safe_globals
source_code = """
import os
os.listdir('/')
"""
byte_code = compile_restricted(source_code, '<inline>', 'exec')
exec(byte_code, safe_globals, {})
Output
Traceback (most recent call last):
File "/home/afsal/Desktop/experiments/restricted_python/no_working.py", line 11, in <module>
exec(byte_code, safe_globals, {})
File "<inline>", line 2, in <module>
ImportError: __import__ not found
How Does It Work?
- Compiles the code to Python bytecode
- Strips out or restricts unsafe features
- Provides a safe set of built-in functions
Great for:
- Online code runners / compilers
- Plugin systems
- Custom business rule scripting
- Safe sandboxing for education
Not great for:
- Full app environments
- Anything requiring I/O, network, or files
Summary
RestrictedPython A sandbox to run safe Python code
Blocks unsafe use Files, OS commands, imports, eval/exec
Use case Untrusted user code, education, plugins