add a py.builtin.execfile helper

--HG--
branch : trunk
This commit is contained in:
Benjamin Peterson 2009-08-29 15:34:24 -05:00
parent c95504e738
commit 39eac1be28
2 changed files with 28 additions and 0 deletions

View File

@ -11,9 +11,25 @@ if sys.version_info >= (3, 0):
obj = obj.encode(encoding)
return str(obj, encoding)
def execfile(fn, globs=None, locs=None):
if globs is None:
back = sys._getframe(1)
globs = back.f_globals
locs = back.f_locals
del back
elif locs is None:
locs = globs
fp = open(fn, "rb")
try:
source = fp.read()
finally:
fp.close()
exec_(source, globs, locs)
else:
_totext = unicode
_basestring = basestring
execfile = execfile
import __builtin__ as builtins
def print_(*args, **kwargs):

View File

@ -84,6 +84,18 @@ def test_print_simple():
s = f.getvalue()
assert s == "xyzabc"
def test_execfile(tmpdir):
test_file = tmpdir.join("test.py")
test_file.write("x = y")
ns = {"y" : 42}
py.builtin.execfile(str(test_file), ns)
assert ns["x"] == 42
class A:
y = 3
x = 4
py.builtin.execfile(str(test_file))
assert A.x == 3
def test_totext():
py.builtin._totext("hello", "UTF-8")