2002-08-09 23:11:12 +02:00
|
|
|
"""Eval python code with global namespace of a python source file."""
|
2002-10-07 23:11:19 +02:00
|
|
|
|
2014-12-23 10:12:23 +01:00
|
|
|
# Copyright (C) 2002-2014 John Goerzen & contributors
|
2002-10-07 23:11:19 +02:00
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
2003-04-16 21:23:45 +02:00
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
2002-10-07 23:11:19 +02:00
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program; if not, write to the Free Software
|
2006-08-12 06:15:55 +02:00
|
|
|
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
2002-10-07 23:11:19 +02:00
|
|
|
|
2003-07-26 04:01:25 +02:00
|
|
|
import imp
|
|
|
|
try:
|
|
|
|
import errno
|
|
|
|
except:
|
|
|
|
pass
|
2002-08-09 23:11:12 +02:00
|
|
|
|
|
|
|
class LocalEval:
|
2014-12-23 10:12:23 +01:00
|
|
|
"""Here is a powerfull but very dangerous option, of course.
|
|
|
|
|
|
|
|
Assume source file to be ASCII encoded."""
|
|
|
|
|
2002-08-09 23:11:12 +02:00
|
|
|
def __init__(self, path=None):
|
2014-12-23 10:12:23 +01:00
|
|
|
self.namespace = {}
|
2002-08-09 23:11:12 +02:00
|
|
|
|
|
|
|
if path is not None:
|
2014-12-23 10:12:23 +01:00
|
|
|
# FIXME: limit opening files owned by current user with rights set
|
|
|
|
# to fixed mode 644.
|
|
|
|
file = open(path, 'r')
|
|
|
|
module = imp.load_module(
|
2002-08-09 23:11:12 +02:00
|
|
|
'<none>',
|
|
|
|
file,
|
|
|
|
path,
|
|
|
|
('', 'r', imp.PY_SOURCE))
|
|
|
|
for attr in dir(module):
|
2014-12-23 10:12:23 +01:00
|
|
|
self.namespace[attr] = getattr(module, attr)
|
2002-08-09 23:11:12 +02:00
|
|
|
|
|
|
|
def eval(self, text, namespace=None):
|
|
|
|
names = {}
|
|
|
|
names.update(self.namespace)
|
|
|
|
if namespace is not None:
|
|
|
|
names.update(namespace)
|
|
|
|
return eval(text, names)
|