- global html_template
- html = html_template.safe_substitute(expr=expr.encode("string-escape"), gcount=gcount, logs=json.dumps(logs).encode("string-escape"))
- with file("expr1.html", "wt") as f:
- f.write(html)
+ # In the Python 2.7 version this used to be str.encode('string-escape'),
+ # which was a normal string, but in Python 3 the "string_escape" encoding
+ # no longer exists and even with the "unicode_escape" encoding encode()
+ # always returns a binary string. So let's just escape the single quotes
+ # here and hope the result is a valid JavaScript string literal.
+ def encode(s):
+ return s.replace("'", "\'")
+
+ mapping = {
+ 'expr_html': html.escape(expr),
+ 'expr_json': encode(expr),
+ 'gcount': gcount,
+ 'logs': encode(json.dumps([s.strip().replace("\n", "<br/>") for s in logs])),
+ }
+ with open("expr1.html", "wt") as f:
+ f.write(html_template.safe_substitute(mapping))