|
1 | 1 | # Generates a JSON trace that is compatible with the js/pytutor.js frontend |
2 | 2 |
|
3 | | -import optparse |
4 | | - |
5 | | -CUMULATIVE_MODE = False |
6 | | - |
7 | | -COMPACT = False |
8 | | -if COMPACT: |
9 | | - INDENT_LEVEL=None |
10 | | -else: |
11 | | - INDENT_LEVEL=2 |
12 | | - |
13 | | - |
14 | 3 | import sys, pg_logger, json |
15 | | - |
| 4 | +from optparse import OptionParser |
16 | 5 |
|
17 | 6 | # To make regression tests work consistently across platforms, |
18 | 7 | # standardize display of floats to 3 significant figures |
|
21 | 10 | # http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module |
22 | 11 | json.encoder.FLOAT_REPR = lambda f: ('%.3f' % f) |
23 | 12 |
|
24 | | - |
25 | 13 | def json_finalizer(input_code, output_trace): |
26 | 14 | ret = dict(code=input_code, trace=output_trace) |
27 | 15 | json_output = json.dumps(ret, indent=INDENT_LEVEL) |
28 | 16 | print(json_output) |
29 | 17 |
|
30 | | - |
31 | 18 | def js_var_finalizer(input_code, output_trace): |
32 | 19 | global JS_VARNAME |
33 | 20 | ret = dict(code=input_code, trace=output_trace) |
34 | 21 | json_output = json.dumps(ret, indent=None) |
35 | 22 | print("var %s = %s;" % (JS_VARNAME, json_output)) |
36 | 23 |
|
37 | | - |
38 | | -parser = optparse.OptionParser() |
| 24 | +parser = OptionParser(usage="Generate JSON trace for pytutor") |
| 25 | +parser.add_option('-c', '--cumulative', default=False, action='store_true', |
| 26 | + help='output cumulative trace.') |
| 27 | +parser.add_option('-o', '--compact', default=False, action='store_true', |
| 28 | + help='output compact trace.') |
39 | 29 | parser.add_option("--create_jsvar", dest="js_varname", |
40 | 30 | help="Create a JavaScript variable out of the trace") |
41 | 31 | (options, args) = parser.parse_args() |
| 32 | +INDENT_LEVEL = None if options.compact else 2 |
| 33 | + |
| 34 | +fin = sys.stdin if args[0] == "-" else open(args[0]) |
42 | 35 |
|
43 | 36 | if options.js_varname: |
44 | 37 | JS_VARNAME = options.js_varname |
45 | | - pg_logger.exec_script_str(open(args[0]).read(), CUMULATIVE_MODE, js_var_finalizer) |
| 38 | + pg_logger.exec_script_str(fin.read(), options.cumulative, js_var_finalizer) |
46 | 39 | else: |
47 | | - pg_logger.exec_script_str(open(args[0]).read(), CUMULATIVE_MODE, json_finalizer) |
| 40 | + pg_logger.exec_script_str(fin.read(), options.cumulative, json_finalizer) |
0 commit comments