Import Python Library

626 views
Skip to first unread message

Ashley Huels

unread,
Nov 29, 2017, 11:35:30 PM11/29/17
to Blockly
The following code throws an "unexpected token import" error when compiled. The import is done the same way that the math block imports the random library though. Any suggestions would be appreciated.

Blockly.Python['postSomething'] = function(block) {
         
     
Blockly.Python.definitions_['import_requests'] = 'import requests';
           
     
var code = "r = requests.post(\"http://localhost:5000/leds/6\")\nprint(r.status_code, r.reason)";
     
return code;
       
};

Neil Fraser

unread,
Nov 30, 2017, 12:19:27 AM11/30/17
to blo...@googlegroups.com
Can you post the Python code that it generates?  That should make the error clear.

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ashley Huels

unread,
Nov 30, 2017, 2:24:43 PM11/30/17
to Blockly
When I code = Blockly.Python.WorkspaceToCode(workspace) and print it it shows the expected code:

import requests


r
= requests.post("http://localhost:5000/leds/6")
print(r.status_code, r.reason)

Neil Fraser

unread,
Nov 30, 2017, 2:52:17 PM11/30/17
to blo...@googlegroups.com
How are you running the generated Python?  "unexpected token import" feels like a JavaScript error, not a Python error.  Are you accidentally executing the Python code in a JavaScript interpreter?

To unsubscribe from this group and stop receiving emails from it, send an email to blockly+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Ashley

unread,
Nov 30, 2017, 5:47:51 PM11/30/17
to Blockly
Yeah when I was looking up the error everything pointed to JS. I basically just have:

function runCode() {
           
   
var code = Blockly.Python.workspaceToCode(workspace);

   
try {
        
eval(code);
     
}catch (e) {
         alert
(e);
     
}
       

}
Enter code here...


Neil Fraser

unread,
Nov 30, 2017, 5:55:49 PM11/30/17
to blo...@googlegroups.com
Right, the problem is eval(code)Eval is a JavaScript function in the browser that expects JavaScript code.

If you want to run Python code, you will need to rethink your overall architecture to include a Python interpreter somewhere.

To unsubscribe from this group and stop receiving emails from it, send an email to blockly+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages