def write_and_import(self, code, modulename='mymodule'):
self.assertTrue('.py' not in modulename)
filename = modulename + '.py'
if isinstance(code, bytes):
code = code.decode('utf-8')
# Be explicit about encoding the temp file as UTF-8 (issue #63):
with io.open(self.tempdir + filename, 'w', encoding='utf-8') as f:
f.write(textwrap.dedent(code).strip() + '\n')
# meta_path_len = len(sys.meta_path)
install_hooks(modulename)
# print('Hooks installed')
# assert len(sys.meta_path) == 1 + meta_path_len
# print('sys.meta_path is: {0}'.format(sys.meta_path))
module = None
sys.path.insert(0, self.tempdir)
try:
module = __import__(modulename)
except SyntaxError:
print('Bombed!')
else:
print('Succeeded!')
finally:
remove_hooks()
# print('Hooks removed')
sys.path.remove(self.tempdir)
return module
评论列表
文章目录