localeval.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Eval python code with global namespace of a python source file."""
  2. # Copyright (C) 2002-2016 John Goerzen & contributors
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. import imp
  18. try:
  19. import errno
  20. except:
  21. pass
  22. class LocalEval(object):
  23. """Here is a powerfull but very dangerous option, of course."""
  24. def __init__(self, path=None):
  25. self.namespace = {}
  26. if path is not None:
  27. # FIXME: limit opening files owned by current user with rights set
  28. # to fixed mode 644.
  29. foo = open(path, 'r')
  30. module = imp.load_module(
  31. '<none>',
  32. foo,
  33. path,
  34. ('', 'r', imp.PY_SOURCE))
  35. for attr in dir(module):
  36. self.namespace[attr] = getattr(module, attr)
  37. def eval(self, text, namespace=None):
  38. names = {}
  39. names.update(self.namespace)
  40. if namespace is not None:
  41. names.update(namespace)
  42. return eval(text, names)