Commit abb91745 by Ned Batchelder

Refactor how script chunks are run.

parent 12b68767
...@@ -18,7 +18,6 @@ import logging ...@@ -18,7 +18,6 @@ import logging
import math import math
import numpy import numpy
import os import os
import random
import re import re
import struct import struct
import sys import sys
...@@ -437,49 +436,42 @@ class LoncapaProblem(object): ...@@ -437,49 +436,42 @@ class LoncapaProblem(object):
Problem XML goes to Python execution context. Runs everything in script tags. Problem XML goes to Python execution context. Runs everything in script tags.
''' '''
random.seed(self.seed)
context = {} context = {}
context['seed'] = self.seed context['seed'] = self.seed
context['script_code'] = '' all_code = ''
self._execute_scripts(tree.findall('.//script'), context)
return context
def _execute_scripts(self, scripts, context): python_path = []
'''
Executes scripts in the given context.
'''
original_path = sys.path
for script in scripts: for script in tree.findall('.//script'):
sys.path = original_path + self._extract_system_path(script)
stype = script.get('type') stype = script.get('type')
if stype: if stype:
if 'javascript' in stype: if 'javascript' in stype:
continue # skip javascript continue # skip javascript
if 'perl' in stype: if 'perl' in stype:
continue # skip perl continue # skip perl
# TODO: evaluate only python # TODO: evaluate only python
python_path.extend(self._extract_system_path(script))
code = script.text code = script.text
XMLESC = {"'": "'", """: '"'} XMLESC = {"'": "'", """: '"'}
code = unescape(code, XMLESC) code = unescape(code, XMLESC)
# store code source in context all_code += code
context['script_code'] += code
if all_code:
try: try:
# use "context" for global context; thus defs in code are global within code
locals_dict = {} locals_dict = {}
safe_exec.safe_exec(code, context, locals_dict) safe_exec.safe_exec(all_code, context, locals_dict, random_seed=self.seed)
context.update(locals_dict) context.update(locals_dict)
except Exception as err: except Exception as err:
log.exception("Error while execing script code: " + code) log.exception("Error while execing script code: " + all_code)
msg = "Error while executing script code: %s" % str(err).replace('<', '&lt;') msg = "Error while executing script code: %s" % str(err).replace('<', '&lt;')
raise responsetypes.LoncapaProblemError(msg) raise responsetypes.LoncapaProblemError(msg)
finally:
sys.path = original_path # store code source in context
context['script_code'] = all_code
return context
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment