import builtins, sys, traceback
from js import document, window

def print(*args, **kwargs):
    output = document.getElementById("output")
    output.innerHTML += "<span style='color: #0f0'>" + " ".join(str(a) for a in args) + "</span><br>"

def handle_exception(exc_type, exc_value, exc_traceback):
    output = document.getElementById("output")
    tb = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
    output.innerHTML += "<span style='color: red'>" + tb.replace("\n", "<br>") + "</span>"

    while exc_traceback.tb_next:
        exc_traceback = exc_traceback.tb_next
    lineno = exc_traceback.tb_lineno
    window.reportPythonErrorLine(lineno)

builtins.print = print
sys.excepthook = handle_exception
