2

If you run this code:

src = "import os"
d = dict(__builtins__={})
exec src in d

Python says:

ImportError: __import__ not found

That's what I like to do, but when creating (or maybe loading) a new module:

import imp
mod = imp.new_module("foo")
src = "import os"
exec src in mod.__dict__

As you can see it runs, but I like it doesn't as in the above program. I like to disable all the built-in variables and functions. Is there any way to do this?

If you print mod.__dict__, you can see that it has __builtins__ variable such as any Python module. I think I have to change its value to {}, but I don't know how.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    So you want to *"disable all the built-in variables and functions"*, but not really *all* of them? What you're doing seems like a bit of a hack; what's led you to this need? – jonrsharpe Jul 03 '15 at 16:59
  • 2
    It sounds like you want to somehow run an arbitrary string in a "safe" environment. Given that you can do things like open files using the os module without having access to the open builtin you should be more clear on what you want. – CrazyCasta Jul 03 '15 at 17:02
  • I like to create a module with restricted __builtins__ global constants and functions (but just in this module), something like the first code (if you change src by "sum([2, 4])" it's an error too because python don't know how to execute this). – Sebastian Alvarez Jul 03 '15 at 17:03
  • 1
    Yes, but **why**? If @CrazyCasta is right and you're trying to do sandboxing, see e.g. http://programmers.stackexchange.com/q/191623/110531 – jonrsharpe Jul 03 '15 at 17:04
  • He seems to be trying to execute something in a restricted environment. Clearly the python-exec tag matches, and given that restrict doesn't have a description I don't really see the problem. – CrazyCasta Jul 03 '15 at 17:04
  • Yes @CrazyCasta, that's what I like to do, creating a "safe" environment – Sebastian Alvarez Jul 03 '15 at 17:04
  • Obviously, if you don't have `__import__` in your module's `__builtins__` you can't use it to import anything. But more likely you want to put `os` object directly in yourself. – o11c Jul 03 '15 at 17:06
  • Yes @Padraic Cunningham, that's what I liked to do. It was very simple. I was trying to change all the __dict__ variable, but I can't because it contains private things. But when I do this, it works nice!! thanks. – Sebastian Alvarez Jul 03 '15 at 17:37
  • @SebastianAlvarez, I added it as an answer when I read your question properly and saw I think *I have to change its value to {}, but I don't know how* ;) – Padraic Cunningham Jul 03 '15 at 17:38

1 Answers1

2

I think I have to change its value to {}, but I don't know how.

mod.__dict__["__builtins__"] = {}
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321