How to execute Python code generated by Blockly right in the browser?

2.9k views Asked by At

I was following the example Blockly Code Generators and was able to generate Python codes. But when I run the Python code, I get an error. It seems the error is 'eval(code)' below, what should I do if I want to execute the Python code right inside the browser? Thanks for any help!

Blockly.JavaScript.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
  eval(code);
} catch (e) {
  alert(e);
}

here is the snapshot Unfortunately i dont have enough points to post the image here

3

There are 3 answers

10
Anand S Kumar On

Can you try this with a simple code , like - print('Hello World!')

According to the image , the issue could be with indentation , and indentation is very important in python, othewise it can cause syntax errors .

You should have also changed the code to -

Blockly.Python.addReservedWords('code');
var code = Blockly.JavaScript.workspaceToCode(workspace);
try {
  eval(code);
} catch (e) {
  alert(e);
}
0
Pratik Patil On

as you using eval function of javascript you are actually saying to print the page as print() means to print the page in javascript.

The solution to this is there in the Blockly itself as to rn the code they call this function.

   function() {
  Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n';
  var timeouts = 0;
  var checkTimeout = function() {
    if (timeouts++ > 1000000) {
      throw MSG['timeout'];
    }
  };
  var code = Blockly.JavaScript.workspaceToCode(Code.workspace);
  Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
  try {
    eval(code);
  } catch (e) {
    alert(MSG['badCode'].replace('%1', e));
  }

The above code is from code.js in demos/code/code.js line 553.

0
Gra On

Try to eval with a Python interp written is JS, like http://brython.info/.