skulpt / skulpt

Skulpt is a Javascript implementation of the Python programming language

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Making a suspendable print function?

bnmnetp opened this issue · comments

OK, its been a while since I've done much hacking on skulpt. But I would like to make my print function suspendable. so that I can catch and stop programs in infinite loops that are generating a lot of output to the web page.

Here is my try:

    outputfun(text) {
        // bnm python 3
        if (this.outputLineCount > 1000) return;
        $(this.output).css("visibility", "visible");
        text = text
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/\n/g, "<br/>");
        // todo: try to make this use the suspension mechanism in skulpt
        return new Sk.misceval.promiseToSuspension(new Promise(function (resolve) {
                setTimeout(
                    function () {
                        if (this.outputLineCount < 1000) {
                            $(this.output).append(text);
                            this.outputLineCount += 1;
                            resolve(Sk.builtin.none.none$)
                        } else {
                            if (this.outputLineCount == 1000) {
                                $(this.output).append("Too Much output");
                                this.outputLineCount += 1;
                                stopExecution = true;
                                resolve(Sk.builtin.none.none$)
                            }
                        }
                    }.bind(this),
                    1
                );
            }.bind(this)
        ));
    }

And I run the program like this...

            await Sk.misceval.asyncToPromise(function () {
                return Sk.importMainWithBody("<stdin>", false, prog, true);
            }, { // suspension handlers
            "*": () => {
                if (stopExecution) {
                    console.log("stopExecution is true")
                    throw new Error(`Too much output`);
                }
            },
            });

Although my output ends up having the message "Too Much output" in it, The console never gets the stopExecution is true message. I've tried adding a console.log("debug") before the if statement in the code above but I don't see that either.

My test program is just:

for i in range(100000):
   print("hello")

Any hints?

Thanks,

Brad

commented

@bnmnetp can you create a jsFiddle or similar to demonstrate so that it's easy to have a play with?