I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?
You can overload the import mechanism. We used this to have a licensing system for plugins, you can easily have a whitelist / blacklist of module names.
Preventing Python code from importing certain modules?