ShungChing
ShungChing

Reputation: 153

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

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

Upvotes: 2

Views: 3203

Answers (3)

Pratik Patil
Pratik Patil

Reputation: 1

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.

Upvotes: 0

Gra
Gra

Reputation: 1594

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

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90999

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);
}

Upvotes: 1

Related Questions