Altered builtins without restricted environment?
Erik Max Francis
max at alcyone.com
Mon Aug 26 11:16:42 CEST 2002
For my project, I'm finding myself want to maintain multiple independent
execution contexts, all of which can independently capture the output of
their execution. Note that this execution need not be restricted at
all; these are specialized scripts being run by the user, so an actual
restricted environment via rexec.RExec is unnecessary.
Since each context is independent, they each have independent globals
dictionaries; fair enough. Since each needs to capture any output, one
can just put fake copies of the sys module in each globals dictionary,
with the sys.stdout substituted with a proxy object that redirects
output to the appropriate place.
But this presents a problem. Since the sys module in each globals
dictionary is not the actual sys module, executing "import sys" in any
of these contexts will replace the dummied-up sys module (containing the
overridden sys.stdout proxy object), wrecking the setup. I'm not
particularly worried about people deliberately trying to mess things up
by, say, rebinding sys.stdout in a particular context, but something as
innocent as attempting to import sys shouldn't cause something that
So it occurred to me a possibility would be to override the builtin
__import__ function inside each of these contexts to check if the 'sys'
module is being imported and then substituted in the (already created
and imported) fake module. But this presents a problem; since each
context has its own fake sys module, that means each context would have
to have its own version of __import__. But this means a different fake
__builtins__ module for each context, and the way that the Python
interpreter determines whether it's in a restricted environment is
whether or not the executed __builtins__ module is the same as the
original. So this results in each context being executed in a
restricted environment, which is what I was trying to avoid in the first
As an intermediate solution, I suppose I could override the (_the_)
__builtins__' __import__ function and make it so that if anything
(including the original script) tries to reimport the 'sys' module it
raises an error with somewhat helpful message (there truly is no point
in reimporting sys in either the main script or any of the executing
contexts). But this is inelegant to say the least.
Is there a better approach to this problem, given that restricted
environment execution is not my goal?
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
Church / http://www.alcyone.com/pyos/church/
A lambda calculus explorer in Python.
More information about the Python-list