Skip to content

Brython as a Python 3 interpreter for activecode #489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bases/rsptx/interactives/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion bases/rsptx/interactives/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"license": "ISC",
"devDependencies": {
"compression-webpack-plugin": "^9.0.0",
"copy-webpack-plugin": "^9.0.0",
"copy-webpack-plugin": "^9.1.0",
"css-loader": "^6.0.0",
"css-minimizer-webpack-plugin": "^3.0.0",
"html-loader": "^3.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def setup(app):
%(hidecode)s %(include)s %(timelimit)s %(coach)s %(codelens)s %(enabledownload)s %(chatcodes)s %(optional)s
data-audio='%(ctext)s' %(sourcefile)s %(datafile)s %(stdin)s %(tie)s %(dburl)s %(nopair)s
%(cargs)s %(largs)s %(rargs)s %(iargs)s %(gradebutton)s %(caption)s %(hidehistory)s %(wasmuri)s
%(showlastsql)s style="visibility: hidden;">
%(showlastsql)s %(python3_interpreter)s style="visibility: hidden;">
%(initialcode)s
</textarea>
</div>
Expand Down Expand Up @@ -224,6 +224,7 @@ class ActiveCode(RunestoneIdDirective):
:nopair: -- disable pair programming features
:dburl: url to load database for sql mode
:showlastsql: -- Only show the last sql result in output
:python3_interpreter: brython (uses brython as interpreter of python3)

If this is a homework problem instead of an example in the text
then the assignment text should go here. The assignment text ends with
Expand Down Expand Up @@ -279,6 +280,7 @@ class ActiveCode(RunestoneIdDirective):
"nopair": directives.flag,
"dburl": directives.unchanged,
"showlastsql": directives.flag,
"python3_interpreter": directives.unchanged,
}
)

Expand Down Expand Up @@ -337,6 +339,11 @@ def run(self):
self.options["ctext"] = newcomplete
self.options["no_of_buttons"] = no_of_buttons

if ("python3_interpreter" in self.options) and (self.options["language"]=="python3") :
self.options["python3_interpreter"] = "data-python3_interpreter='%s'" % self.options["python3_interpreter"]
else:
self.options["python3_interpreter"] = ""

if "caption" not in self.options:
self.options["caption"] = ""
else:
Expand Down
12 changes: 11 additions & 1 deletion bases/rsptx/interactives/runestone/activecode/js/acfactory.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { ActiveCode } from "./activecode.js";
import JSActiveCode from "./activecode_js.js";
import HTMLActiveCode from "./activecode_html.js";
import SQLActiveCode from "./activecode_sql.js";
import BrythonActiveCode from "./activecode_brython.js";
import LiveCode from "./livecode.js";
import {
TimedActiveCode,
TimedLiveCode,
TimedJSActiveCode,
TimedHTMLActiveCode,
TimedSQLActiveCode,
TimedBrythonActiveCode,
} from "./timed_activecode";
import "../../common/js/jquery.highlight.js";

Expand All @@ -30,7 +32,12 @@ export default class ACFactory {
if (lang === undefined) {
lang = $(opts.orig).find("[data-lang]").data("lang");
}
var text_area = $(opts.orig).find("textarea")[0]
var python3_interpreter = $(text_area).attr("data-python3_interpreter");
if (opts.timed == true) {
if(python3_interpreter==="brython"){
return new TimedBrythonActiveCode(opts);
}
if (lang === "python") {
return new TimedActiveCode(opts);
} else if (
Expand All @@ -40,7 +47,10 @@ export default class ACFactory {
lang === "python3"
) {
return new TimedLiveCode(opts);
} else if (lang === "javascript") {
} else if ((lang ==="python3") && (python3_interpreter === "brython")){
return new BrythonActiveCode(opts);
}
else if (lang === "javascript") {
return new TimedJSActiveCode(opts);
} else if (lang === "htmlmixed") {
return new TimedHTMLActiveCode(opts);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export class ActiveCode extends RunestoneBase {
this.question = $(opts.orig).find(`#${this.divid}_question`)[0];
this.tie = $(orig).data("tie");
this.dburl = $(orig).data("dburl");
this.python3_interpreter = $(orig).data("python3_interpreter");
this.runButton = null;
this.enabledownload = $(orig).data("enabledownload");
this.downloadButton = null;
Expand Down Expand Up @@ -364,15 +365,15 @@ export class ActiveCode extends RunestoneBase {
$(butt).click(this.createGradeSummary.bind(this));
}

addDownloadButton(ctrlDiv) {
addDownloadButton(ctrlDiv) {
let butt = document.createElement("button");
$(butt).text("Download");
$(butt).addClass("btn save-button");
ctrlDiv.appendChild(butt);
this.downloadButton = butt;
$(butt).click(this.downloadFile.bind(this, this.language));
$(butt).attr("type", "button");
}
}

enableHideShow(ctrlDiv) {
$(this.runButton).attr("disabled", "disabled");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { ActiveCode } from "./activecode.js";

export default class BrythonActiveCode extends ActiveCode {
constructor(opts) {
super(opts);
opts.alignVertical = true;
this.python3_interpreter = $(orig).data("python3_interpreter");
$(this.runButton).text("Render");
this.editor.setValue(this.code);
}

async runProg() {
var prog = await this.buildProg(true);
let saveCode = "True";
this.saveCode = await this.manage_scrubber(saveCode);
$(this.output).text("");
if (!this.alignVertical) {
$(this.codeDiv).switchClass("col-md-12", "col-md-6", {
duration: 500,
queue: false,
});
}
$(this.outDiv).show({ duration: 700, queue: false });
prog = `
<html>
<head>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/brython.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/brython_stdlib.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js"></script>
<style>
pre {
position: absolute; font-size: 13px; width: 94%; padding: 9.5px; line-height: 1.42857143; border: 1px ; border-radius: 4px;
}
code{
border: 1px solid #ccc; border-radius: 4px;
}
</style>
</head>
<body onload='brython()' >
<pre id="consolePre">
<code id="consoleCode"></code>
</pre>
<script type='text/python'>
import sys
from browser import document, html
logger = document['consoleCode']
preElem = document['consolePre']
class NewOut:
def write(self, data):
logger.innerHTML += str(data)
sys.stderr = sys.stdout = NewOut()
</script>
<script type="text/python3">
from browser import document, html
import sys
import traceback
def my_exec(code):
try:
exec(code, locals())
preElem = document['consolePre']
preElem.style.visibility = "visible"
preElem.style.bottom = "5px"
document['consoleCode'].classList.add("plaintext")
except SyntaxError as err:
error_class = err.__class__.__name__
detail = err.args[0]
line_number = f"at line {err.lineno}"
except BaseException as err:
error_class = err.__class__.__name__
detail = err.args[0]
cl, exc, tb = sys.exc_info()
# When errors don't specify a line
try:
line_number = f"at line {traceback.extract_tb(tb)[-1][1]}"
except:
line_number = ""
else:
return

# This is only done if an Exception was catched
result = f"'{error_class}': {detail} {line_number}"
print(result)
logger = document['consoleCode']
preElem = document['consolePre']
# Styling the pre element for error
error_header = document.createElement("h3")
error_header.innerHTML = "Error"
error_header.style.font = "24px 'Arial'"
preElem.prepend(error_header)
preElem.style.visibility = "visible"
preElem.style.top = "5px"
preElem.style.backgroundColor = "#f2dede"
preElem.style.border = "1px solid #ebccd1"
logger.classList.add("python")
my_exec("""${prog}
""")
document <= html.SCRIPT("hljs.highlightAll();")
</script>
</body>
</html>
`;
this.output.srcdoc = prog;
}

createOutput() {
this.alignVertical = true;
var outDiv = document.createElement("div");
$(outDiv).addClass("ac_output");
if (this.alignVertical) {
$(outDiv).addClass("col-md-12");
} else {
$(outDiv).addClass("col-md-5");
}
this.outDiv = outDiv;
this.output = document.createElement("iframe");
$(this.output).css("background-color", "white");
$(this.output).css("position", "relative");
$(this.output).css("height", "400px");
$(this.output).css("width", "100%");
outDiv.appendChild(this.output);
this.outerDiv.appendChild(outDiv);
var clearDiv = document.createElement("div");
$(clearDiv).css("clear", "both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
}
enableSaveLoad() {
$(this.runButton).text($.i18n("msg_activecode_render"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ActiveCode } from "./activecode";
import JSActiveCode from "./activecode_js";
import HTMLActiveCode from "./activecode_html";
import SQLActiveCode from "./activecode_sql";
import BrythonActiveCode from "./activecode_brython.js";

var TimedActiveCodeMixin = {
timedInit: async function (opts) {
Expand Down Expand Up @@ -143,3 +144,11 @@ export class TimedSQLActiveCode extends SQLActiveCode {
}
}
Object.assign(TimedSQLActiveCode.prototype, TimedActiveCodeMixin);

export class TimedBrythonActiveCode extends BrythonActiveCode {
constructor(opts) {
super(opts);
this.timedInit(opts);
}
}
Object.assign(TimedBrythonActiveCode.prototype, TimedActiveCodeMixin);
Original file line number Diff line number Diff line change
Expand Up @@ -2834,3 +2834,18 @@ Support for SQL in the browser ? Yes!
}

} // end of World class

Trying Brython as Python 3 interpreter
--------------------------------------
.. activecode:: test_activecode_python3
:language: python3
:python3_interpreter: brython

print("You can see this print inside the iframe console")
from browser import document, alert, html

def hello(ev):
alert("Hello! I'm using Brython :D")

document <= html.BUTTON("My button", id="button_alert")
document["button_alert"].bind("click", hello)
85 changes: 0 additions & 85 deletions sample.env

This file was deleted.