Example #1
0
def execute(test_script):
  def my_finalizer(output_lst):
    outfile = open(test_script[:-3] + '.out', 'w')
    output_json = json.dumps(output_lst)
    print >> outfile, output_json

  pg_logger.exec_script_str(open(test_script).read(), my_finalizer, True)
Example #2
0
def main():
    script_name = sys.argv[1]
    output_name = script_name + '.heapviz.html'
    
    user_script = read_file(script_name)
    template = read_file('heapviz.html')
    
    output = open(output_name, 'wt')
    try:
        starting_instruction = '-1'
        if len(sys.argv) > 2:
            starting_instruction = sys.argv[2]
        
        json_output = ''
        def output_handler(input_code, output_trace):
            nonlocal json_output
            ret = dict(code=input_code, trace=output_trace)
            json_output += json.dumps(ret, indent=None)
        
        cumulative_mode = False
        pg_logger.exec_script_str(user_script, cumulative_mode, output_handler)
    
        template = template.replace('${JSON_TRACE}', json_output)
        template = template.replace('${STARTING_INSTRUCTION}', starting_instruction);
        print(template, file=output)
    finally:
        output.close()
Example #3
0
def main():
    script_name = sys.argv[1]
    output_name = script_name + '.heapviz.html'

    user_script = read_file(script_name)
    template = read_file('heapviz.html')

    output = open(output_name, 'wt')
    try:
        starting_instruction = '-1'
        if len(sys.argv) > 2:
            starting_instruction = sys.argv[2]

        json_output = ''

        def output_handler(input_code, output_trace):
            nonlocal json_output
            ret = dict(code=input_code, trace=output_trace)
            json_output += json.dumps(ret, indent=None)

        cumulative_mode = False
        pg_logger.exec_script_str(user_script, cumulative_mode, output_handler)

        template = template.replace('${JSON_TRACE}', json_output)
        template = template.replace('${STARTING_INSTRUCTION}',
                                    starting_instruction)
        print(template, file=output)
    finally:
        output.close()
def execute(test_script):
  def my_finalizer(output_lst):
    outfile = open(test_script[:-3] + '.out', 'w')
    output_json = demjson.encode(output_lst, compactly=False)
    print >> outfile, output_json

  pg_logger.exec_script_str(open(test_script).read(), my_finalizer, True)
Example #5
0
def execute(test_script):
    def my_finalizer(output_lst):
        outfile = open(test_script[:-3] + ".out", "w")
        output_json = json.dumps(output_lst)
        print >> outfile, output_json

    pg_logger.exec_script_str(open(test_script).read(), my_finalizer, True)
  def get(self):
    self.response.headers['Content-Type'] = 'application/json'
    self.response.headers['Cache-Control'] = 'no-cache'

    pg_logger.exec_script_str(self.request.get('user_script'),
                              self.request.get('raw_input_json'),
                              self.request.get('options_json'),
                              self.json_finalizer)
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        self.response.headers['Cache-Control'] = 'no-cache'

        pg_logger.exec_script_str(self.request.get('user_script'),
                                  self.request.get('raw_input_json'),
                                  self.request.get('options_json'),
                                  self.json_finalizer)
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        self.response.headers['Cache-Control'] = 'no-cache'

        # convert from string to a Python boolean ...
        cumulative_mode = (self.request.get('cumulative_mode') == 'true')

        pg_logger.exec_script_str(self.request.get('user_script'),
                                  cumulative_mode, self.json_finalizer)
  def get(self):
    self.response.headers['Content-Type'] = 'application/json'
    self.response.headers['Cache-Control'] = 'no-cache'

    # convert from string to a Python boolean ...
    cumulative_mode = (self.request.get('cumulative_mode') == 'true')
    
    pg_logger.exec_script_str(self.request.get('user_script'),
                              cumulative_mode,
                              self.json_finalizer)
Example #10
0
  def execute_code(self, user_script, raw_input_json, options_json):

    print 'execting code ...'
    print '--------------------------------------------------------------------------------'
    print 'user_script: ', user_script
    print 'raw_input_json: ', raw_input_json
    print 'options_json: ', options_json
    print '--------------------------------------------------------------------------------'

    pg_logger.exec_script_str(
      user_script,
      raw_input_json,
      options_json,
      self.json_finalizer)

    print 'json_output: ', self.json_output
    print '--------------------------------------------------------------------------------'
Example #11
0
    def run(self):
        self.options['divid'] = self.arguments[0]
        if self.content:
            source = "\n".join(self.content)
        else:
            source = '\n'

        tdata = exec_script_str(source,web_finalizer)
        self.options['tracedata'] = tdata
        self.options['pycode'] = json.dumps(source)
        res = VIS
        if 'caption' not in self.options:
            self.options['caption'] = ''
        if 'tracedata' in self.options:
            res += DATA

        return [nodes.raw('',res % self.options,format='html')]
Example #12
0
    def run(self):
        self.options["divid"] = self.arguments[0]
        if self.content:
            source = "\n".join(self.content)
        else:
            source = "\n"

        tdata = exec_script_str(source, web_finalizer)
        self.options["tracedata"] = tdata
        self.options["pycode"] = json.dumps(source)
        res = VIS
        if "caption" not in self.options:
            self.options["caption"] = ""
        if "tracedata" in self.options:
            res += DATA

        return [nodes.raw("", res % self.options, format="html")]
Example #13
0
                  os.environ.get("HTTP_REFERER", "N/A"),
                  user_script,
                  int(cumulative_mode))
      con.commit()
      cur.close()
    except:
      # this is bad form, but silently fail on error ...
      pass

  print("Content-type: text/plain; charset=iso-8859-1\n")
  print(json_output)


cumulative_mode = False

# If you pass in a filename as an argument, then process script from that file ...
if len(sys.argv) > 1:
  user_script = open(sys.argv[1]).read()

# Otherwise act like a CGI script with parameters:
#   user_script
#   cumulative_mode
else:
  form = cgi.FieldStorage()
  user_script = form['user_script'].value
  if 'cumulative_mode' in form:
    # convert from string to a Python boolean ...
    cumulative_mode = (form['cumulative_mode'].value == 'true')

pg_logger.exec_script_str(user_script, cumulative_mode, cgi_finalizer)
Example #14
0
# http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
json.encoder.FLOAT_REPR = lambda f: ('%.3f' % f)


def json_finalizer(input_code, output_trace):
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(ret, indent=INDENT_LEVEL)
    print(json_output)


def js_var_finalizer(input_code, output_trace):
    global JS_VARNAME
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(ret, indent=None)
    print("var %s = %s;" % (JS_VARNAME, json_output))


parser = optparse.OptionParser()
parser.add_option("--create_jsvar",
                  dest="js_varname",
                  help="Create a JavaScript variable out of the trace")
(options, args) = parser.parse_args()

if options.js_varname:
    JS_VARNAME = options.js_varname
    pg_logger.exec_script_str(
        open(args[0]).read(), CUMULATIVE_MODE, js_var_finalizer)
else:
    pg_logger.exec_script_str(
        open(args[0]).read(), CUMULATIVE_MODE, json_finalizer)
# standardize display of floats to 3 significant figures
#
# Trick from:
# http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
json.encoder.FLOAT_REPR = lambda f: ('%.3f' % f)


def json_finalizer(input_code, output_trace):
  ret = dict(code=input_code, trace=output_trace)
  json_output = json.dumps(ret, indent=INDENT_LEVEL)
  print(json_output)


def js_var_finalizer(input_code, output_trace):
  global JS_VARNAME
  ret = dict(code=input_code, trace=output_trace)
  json_output = json.dumps(ret, indent=None)
  print("var %s = %s;" % (JS_VARNAME, json_output))


parser = optparse.OptionParser()
parser.add_option("--create_jsvar", dest="js_varname",
                  help="Create a JavaScript variable out of the trace")
(options, args) = parser.parse_args()

if options.js_varname:
  JS_VARNAME = options.js_varname
  pg_logger.exec_script_str(open(args[0]).read(), CUMULATIVE_MODE, js_var_finalizer)
else:
  pg_logger.exec_script_str(open(args[0]).read(), CUMULATIVE_MODE, json_finalizer)
Example #16
0
        else:
            ret['status'] = 'error'
            ret['error_msg'] = user_trace_final_entry['exception_msg']

    # Crucial first line to make sure that Apache serves this data
    # correctly - DON'T FORGET THE EXTRA NEWLINES!!!:
    print "Content-type: text/plain; charset=iso-8859-1\n\n"
    output_json = demjson.encode(ret, compactly=True)
    print output_json


form = cgi.FieldStorage()
user_script = form['user_script'].value
expect_script = form['expect_script'].value

# WEIRD: always run the expect_script FIRST since it's less likely to have
# errors.  for some mysterious reason, if there's an error in user_script,
# then it will never run expect_script
#
# also make sure to ignore IDs so that we can do direct object comparisons!
pg_logger.exec_script_str(expect_script,
                          expect_script_finalizer,
                          ignore_id=True)

# set a custom instruction limit only for user scripts ...
if 'max_instructions' in form:
    pg_logger.set_max_executed_lines(int(form['max_instructions'].value))

pg_logger.exec_script_str(user_script, user_script_finalizer, ignore_id=True)
# Generates a JSON trace that is compatible with the js/pytutor.js frontend

CUMULATIVE_MODE = False


import sys, pg_logger, json


def json_finalizer(input_code, output_trace):
  ret = dict(code=input_code, trace=output_trace)
  json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr
  print(json_output)


for f in sys.argv[1:]:
  pg_logger.exec_script_str(open(f).read(), CUMULATIVE_MODE, json_finalizer)

    else:
      ret['status'] = 'error'
      ret['error_msg'] = user_trace_final_entry['exception_msg']


  # Crucial first line to make sure that Apache serves this data
  # correctly - DON'T FORGET THE EXTRA NEWLINES!!!:
  print "Content-type: text/plain; charset=iso-8859-1\n\n"
  output_json = demjson.encode(ret, compactly=True)
  print output_json


form = cgi.FieldStorage()
user_script = form['user_script'].value
expect_script = form['expect_script'].value

# WEIRD: always run the expect_script FIRST since it's less likely to have
# errors.  for some mysterious reason, if there's an error in user_script,
# then it will never run expect_script
#
# also make sure to ignore IDs so that we can do direct object comparisons!
pg_logger.exec_script_str(expect_script, expect_script_finalizer, ignore_id=True)


# set a custom instruction limit only for user scripts ...
if 'max_instructions' in form:
  pg_logger.set_max_executed_lines(int(form['max_instructions'].value))

pg_logger.exec_script_str(user_script, user_script_finalizer, ignore_id=True)
Example #19
0
def exec_script_str(user_script, raw_input_json, options_json, pipe):
    sys.stdout = WrapperPipeToStdout(pipe)
    pg_logger.exec_script_str(user_script, raw_input_json, options_json, json_finalizer)
Example #20
0
import sys
import pg_logger
import json


def json_finalizer(input_code, output_trace):
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(
        ret, indent=None)  # use indent=None for most compact repr
    print(json_output)


fin = open(sys.argv[1])

pg_logger.exec_script_str(fin.read(), False, json_finalizer)
Example #21
0
    except Exception as err:
      # this is bad form, but silently fail on error ...
      print(err)

  print("Content-type: text/plain; charset=iso-8859-1\n")
  print(json_output)

raw_input_json = None
options_json = None

# If you pass in a filename as an argument, then process script from that file ...
if len(sys.argv) > 1:
  user_script = open(sys.argv[1]).read()

# Otherwise act like a CGI script with parameters:
#   user_script
#   raw_input_json
#   options_json
else:
  form = cgi.FieldStorage()
  user_script = form['user_script'].value
  # for Python 2, immediately convert to utf-8 before passing input into program
  if hasattr(user_script, 'decode'):
    user_script = user_script.decode('utf-8')
  if 'raw_input_json' in form:
    raw_input_json = form['raw_input_json'].value
  if 'options_json' in form:
    options_json = form['options_json'].value

pg_logger.exec_script_str(user_script, raw_input_json, options_json, cgi_finalizer)
Example #22
0
def main():
  usage = "usage: %prog [options] python_file"
  parser = OptionParser(usage=usage)

  parser.add_option("", "--bare", action="store_true", dest="bare", default=False,
                    help="Bare display (for embedding)")

  parser.add_option("", "--end", action="store_true", dest="end", default=False,
                    help="Skip to end")

  parser.add_option("", "--offline", action="store_true", dest="offline", default=False,
                    help="Generate output for offline use")

  parser.add_option("", "--output", action="store_true", dest="output", default=False,
                    help="Show program output")

  parser.add_option("", "--step", dest="step", default=0,
                    help="Starting step (default: 0)")

  (options, args) = parser.parse_args()
  if not args:
    print >> sys.stderr, parser.get_usage()
    sys.exit(1)

  filepath = args[0]

  def cgi_finalizer(input_code, output_trace):
    """Write JSON output for js/pytutor.js as a CGI result."""
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr

    if LOG_QUERIES:
      # just to be paranoid, don't croak the whole program just
      # because there's some error in logging it to the database
      try:
        # log queries into sqlite database.
        # make sure that your web server's account has write permissions
        # in the current directory, for logging to work properly
        con = sqlite3.connect(create_log_db.DB_FILE)
        cur = con.cursor()

        cur.execute("INSERT INTO query_log VALUES (NULL, ?, ?, ?, ?, ?, ?)",
                    (datetime.datetime.now(),
                     os.environ.get("REMOTE_ADDR", "N/A"),
                     os.environ.get("HTTP_USER_AGENT", "N/A"),
                     os.environ.get("HTTP_REFERER", "N/A"),
                     user_script,
                     int(cumulative_mode)))
        con.commit()
        cur.close()
      except Exception as err:
        # this is bad form, but silently fail on error ...
        print(err)

    header = "" if options.bare else HEADERFMT % {"filepath": filepath}
    print IFRAMEFMT % {"traceOutput": json_output,
                       "embeddedMode": "false" if options.output else "true",
                       "startingInstruction": options.step,
                       "jumpToEnd": "true" if options.end else "false",
                       "staticURL": OFFLINE_STATIC_URL if options.offline else ONLINE_STATIC_URL,
                       "editCodeBaseURL": "",
                       "header": header}

  cumulative_mode = False

  if not os.path.exists(filepath) and not os.path.isabs(filepath):
    def_filepath = os.path.normpath(os.path.join(os.path.dirname(__file__), "example-code", filepath))
    if not def_filepath.endswith(".py") and not def_filepath.endswith(".txt"):
      def_filepath += ".txt"
    if os.path.exists(def_filepath):
      filepath = def_filepath
    else:
      print >> sys.stderr, "File %s not found" % filepath
      
  # Process script from file ...
  user_script = open(filepath).read()

  # Ensure that the file compiles
  compile(user_script, filepath, "exec")

  pg_logger.exec_script_str(user_script, cumulative_mode, cgi_finalizer)
Example #23
0
def exec_script_str(user_script, raw_input_json, options_json, pipe):
    sys.stdout = WrapperPipeToStdout(pipe)
    pg_logger.exec_script_str(user_script, raw_input_json, options_json, json_finalizer)
    global JS_VARNAME
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(ret, indent=None)
    print("var %s = %s;" % (JS_VARNAME, json_output))


parser = OptionParser(usage="Generate JSON trace for pytutor")
parser.add_option('-c',
                  '--cumulative',
                  default=False,
                  action='store_true',
                  help='output cumulative trace.')
parser.add_option('-o',
                  '--compact',
                  default=False,
                  action='store_true',
                  help='output compact trace.')
parser.add_option("--create_jsvar",
                  dest="js_varname",
                  help="Create a JavaScript variable out of the trace")
(options, args) = parser.parse_args()
INDENT_LEVEL = None if options.compact else 2

fin = sys.stdin if args[0] == "-" else open(args[0])

if options.js_varname:
    JS_VARNAME = options.js_varname
    pg_logger.exec_script_str(fin.read(), options.cumulative, js_var_finalizer)
else:
    pg_logger.exec_script_str(fin.read(), options.cumulative, json_finalizer)
Example #25
0
    before += '\n\n'
    before += test

    if combiner_func is not '':
        after += '\n\n'
        after += combiner_func

    if key == 'add_three' or key == 'repeated':
        after += '\n\n'
        after += "def identity(x):\n  return x"

    if term_func is not '':
        after += '\n\n'
        after += term_func

    after += '\n\n'
    after += test

    beforeTraces = pg_logger.exec_script_str(before).trace
    afterTraces = pg_logger.exec_script_str(after).trace
    item['beforeCode'] = before
    item['afterCode'] = after
    item['beforeTraces'] = beforeTraces
    item['afterTraces'] = afterTraces

with open('./examples/' + question_type + '_example.json', 'w') as file:
    json.dump([items[0]], file, indent=2)

with open(path, 'w') as file:
    json.dump(items, file)
Example #26
0
      if len(output_lst):
        evt = output_lst[-1]['event']
        if evt == 'exception' or evt == 'uncaught_exception':
          had_error = True

      (con, cur) = db_common.db_connect()
      cur.execute("INSERT INTO query_log VALUES (NULL, ?, ?, ?, ?, ?)",
                  (int(time.time()),
                   os.environ.get("REMOTE_ADDR", "N/A"),
                   os.environ.get("HTTP_USER_AGENT", "N/A"),
                   user_script,
                   had_error))
      con.commit()
      cur.close()
    except:
      # haha this is bad form, but silently fail on error :)
      pass

  # Crucial first line to make sure that Apache serves this data
  # correctly - DON'T FORGET THE EXTRA NEWLINES!!!:
  print "Content-type: text/plain; charset=iso-8859-1\n\n"
  print output_json


form = cgi.FieldStorage()
user_script = form['user_script'].value
if 'max_instructions' in form:
  pg_logger.set_max_executed_lines(int(form['max_instructions'].value))

pg_logger.exec_script_str(user_script, web_finalizer)
Example #27
0
            cur.close()
        except Exception as err:
            # this is bad form, but silently fail on error ...
            print(err)

    print("Content-type: text/plain; charset=iso-8859-1\n")
    print(json_output)


cumulative_mode = False
heap_primitives = False

# If you pass in a filename as an argument, then process script from that file ...
if len(sys.argv) > 1:
    user_script = open(sys.argv[1]).read()

# Otherwise act like a CGI script with parameters:
#   user_script
#   cumulative_mode
else:
    form = cgi.FieldStorage()
    user_script = form['user_script'].value
    if 'cumulative_mode' in form:
        # convert from string to a Python boolean ...
        cumulative_mode = (form['cumulative_mode'].value == 'true')
    if 'heap_primitives' in form:
        heap_primitives = (form['heap_primitives'].value == 'true')

pg_logger.exec_script_str(user_script, cumulative_mode, heap_primitives,
                          cgi_finalizer)
# Generates a JSON trace that is compatible with the js/pytutor.js frontend

import sys, pg_logger, json, os
from optparse import OptionParser

COMPACT = True
INDENT_LEVEL=None if COMPACT else 2


def json_finalizer(input_code, output_trace):
  ret = dict(code=input_code, trace=output_trace)
  json_output = json.dumps(ret, indent=INDENT_LEVEL)
  print(json_output)


parser = OptionParser(usage="Generate JSON trace for pytutor")
parser.add_option('-c', '--cumulative', default=False, action='store_true',
        help='output cumulative trace.')
options, args = parser.parse_args()

for f in args:
  fin = sys.stdin if f == "-" else open(f)
  pg_logger.exec_script_str(fin.read(), options.cumulative, json_finalizer)
Example #29
0
import sys
import pg_logger
import json


def json_finalizer(input_code, output_trace):
  ret = dict(code=input_code, trace=output_trace)
  json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr
  print(json_output)


fin = open(sys.argv[1])

pg_logger.exec_script_str(fin.read(), False, json_finalizer)
Example #30
0
            #  this directory for logging to work properly)
            if len(output_lst):
                evt = output_lst[-1]['event']
                if evt == 'exception' or evt == 'uncaught_exception':
                    had_error = True

            (con, cur) = db_common.db_connect()
            cur.execute(
                "INSERT INTO query_log VALUES (NULL, ?, ?, ?, ?, ?)",
                (int(time.time()), os.environ.get("REMOTE_ADDR", "N/A"),
                 os.environ.get("HTTP_USER_AGENT",
                                "N/A"), user_script, had_error))
            con.commit()
            cur.close()
        except:
            # haha this is bad form, but silently fail on error :)
            pass

    # Crucial first line to make sure that Apache serves this data
    # correctly - DON'T FORGET THE EXTRA NEWLINES!!!:
    print "Content-type: text/plain; charset=iso-8859-1\n\n"
    print output_json


form = cgi.FieldStorage()
user_script = form['user_script'].value
if 'max_instructions' in form:
    pg_logger.set_max_executed_lines(int(form['max_instructions'].value))

pg_logger.exec_script_str(user_script, web_finalizer)
Example #31
0
 def output_dict(self):
     pg_logger.exec_script_str(self.__code, False, False,
                               self.json_finalizer)
     return self.__output
Example #32
0
def main():
    usage = "usage: %prog [options] python_file"
    parser = OptionParser(usage=usage)

    parser.add_option("",
                      "--bare",
                      action="store_true",
                      dest="bare",
                      default=False,
                      help="Bare display (for embedding)")

    parser.add_option("",
                      "--end",
                      action="store_true",
                      dest="end",
                      default=False,
                      help="Skip to end")

    parser.add_option("",
                      "--offline",
                      action="store_true",
                      dest="offline",
                      default=False,
                      help="Generate output for offline use")

    parser.add_option("",
                      "--output",
                      action="store_true",
                      dest="output",
                      default=False,
                      help="Show program output")

    parser.add_option("",
                      "--step",
                      dest="step",
                      default=0,
                      help="Starting step (default: 0)")

    (options, args) = parser.parse_args()
    if not args:
        print >> sys.stderr, parser.get_usage()
        sys.exit(1)

    filepath = args[0]

    def cgi_finalizer(input_code, output_trace):
        """Write JSON output for js/pytutor.js as a CGI result."""
        ret = dict(code=input_code, trace=output_trace)
        json_output = json.dumps(
            ret, indent=None)  # use indent=None for most compact repr

        if LOG_QUERIES:
            # just to be paranoid, don't croak the whole program just
            # because there's some error in logging it to the database
            try:
                # log queries into sqlite database.
                # make sure that your web server's account has write permissions
                # in the current directory, for logging to work properly
                con = sqlite3.connect(create_log_db.DB_FILE)
                cur = con.cursor()

                cur.execute(
                    "INSERT INTO query_log VALUES (NULL, ?, ?, ?, ?, ?, ?)",
                    (datetime.datetime.now(),
                     os.environ.get("REMOTE_ADDR", "N/A"),
                     os.environ.get("HTTP_USER_AGENT", "N/A"),
                     os.environ.get("HTTP_REFERER",
                                    "N/A"), user_script, int(cumulative_mode)))
                con.commit()
                cur.close()
            except Exception as err:
                # this is bad form, but silently fail on error ...
                print(err)

        header = "" if options.bare else HEADERFMT % {"filepath": filepath}
        print IFRAMEFMT % {
            "traceOutput": json_output,
            "embeddedMode": "false" if options.output else "true",
            "startingInstruction": options.step,
            "jumpToEnd": "true" if options.end else "false",
            "staticURL":
            OFFLINE_STATIC_URL if options.offline else ONLINE_STATIC_URL,
            "editCodeBaseURL": "",
            "header": header
        }

    cumulative_mode = False

    if not os.path.exists(filepath) and not os.path.isabs(filepath):
        def_filepath = os.path.normpath(
            os.path.join(os.path.dirname(__file__), "example-code", filepath))
        if not def_filepath.endswith(".py") and not def_filepath.endswith(
                ".txt"):
            def_filepath += ".txt"
        if os.path.exists(def_filepath):
            filepath = def_filepath
        else:
            print >> sys.stderr, "File %s not found" % filepath

    # Process script from file ...
    user_script = open(filepath).read()

    # Ensure that the file compiles
    compile(user_script, filepath, "exec")

    pg_logger.exec_script_str(user_script, cumulative_mode, cgi_finalizer)
Example #33
0
 def pytutor(self, line, cell):
     code, trace = pg_logger.exec_script_str(cell, False)
     result = dict(code=code, trace=trace, handler='pytutor')
     data = jsonapi.dumps(result)
     publish_json(data)
      cur.close()
    except Exception as err:
      # this is bad form, but silently fail on error ...
      print(err)

  print("Content-type: text/plain; charset=iso-8859-1\n")
  print(json_output)


cumulative_mode = False
heap_primitives = False

# If you pass in a filename as an argument, then process script from that file ...
if len(sys.argv) > 1:
  user_script = open(sys.argv[1]).read()

# Otherwise act like a CGI script with parameters:
#   user_script
#   cumulative_mode
else:
  form = cgi.FieldStorage()
  user_script = form['user_script'].value
  if 'cumulative_mode' in form:
    # convert from string to a Python boolean ...
    cumulative_mode = (form['cumulative_mode'].value == 'true')
  if 'heap_primitives' in form:
    heap_primitives = (form['heap_primitives'].value == 'true')


pg_logger.exec_script_str(user_script, cumulative_mode, heap_primitives, cgi_finalizer)
Example #35
0
import json
import sys
import imp

sys.path[0:0] = '.'
import pg_logger  # we mean the one in OnlinePythonTutor/v3

raw_input_json = None
options_json = None

input = sys.stdin.read()

form = json.loads(input)


def finalizer(input_code, output_trace):
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(
        ret, indent=None)  # use indent=None for most compact repr
    print(json_output, end='')


user_script = form['user_script']
if 'raw_input_json' in form:
    raw_input_json = form['raw_input_json']
if 'options_json' in form:
    options_json = form['options_json']

pg_logger.exec_script_str(user_script, raw_input_json, options_json, finalizer)
Example #36
0
# Generates a JSON trace that is compatible with the js/pytutor.js frontend

CUMULATIVE_MODE = False

COMPACT = False
if COMPACT:
    INDENT_LEVEL = None
else:
    INDENT_LEVEL = 2

import sys, pg_logger, json

# To make regression tests work consistently across platforms,
# standardize display of floats to 3 significant figures
#
# Trick from:
# http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
json.encoder.FLOAT_REPR = lambda f: ('%.3f' % f)


def json_finalizer(input_code, output_trace):
    ret = dict(code=input_code, trace=output_trace)
    json_output = json.dumps(ret, indent=INDENT_LEVEL)
    print(json_output)


for f in sys.argv[1:]:
    pg_logger.exec_script_str(open(f).read(), CUMULATIVE_MODE, json_finalizer)