localeval.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 importlib.util
  18. class LocalEval:
  19. """Here is a powerfull but very dangerous option, of course."""
  20. def __init__(self, path=None):
  21. self.namespace = {}
  22. if path is not None:
  23. # FIXME: limit opening files owned by current user with rights set
  24. # to fixed mode 644.
  25. importlib.machinery.SOURCE_SUFFIXES.append('') # empty string to allow any file
  26. spec = importlib.util.spec_from_file_location('<none>', path)
  27. module = importlib.util.module_from_spec(spec)
  28. spec.loader.exec_module(module)
  29. for attr in dir(module):
  30. self.namespace[attr] = getattr(module, attr)
  31. def eval(self, text, namespace=None):
  32. names = {}
  33. names.update(self.namespace)
  34. if namespace is not None:
  35. names.update(namespace)
  36. return eval(text, names)