Skip to content

Commit ce4473b

Browse files
committed
Fix js.py readFileSync, add isbrowser variable after init_python, etc
1 parent d112536 commit ce4473b

File tree

3 files changed

+41
-18
lines changed

3 files changed

+41
-18
lines changed

README.md

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,26 +99,30 @@ init_python(stack_size)
9999
NEW!! This function execute js.py to expose JS API to Python, even some helper function and experimental asynchronous queue/stack logic. Example:
100100

101101
```javascript
102-
import mp_js from 'micropython';
102+
mp_js = require('micropython');
103103

104104
(async () => {
105105
await mp_js;
106106
await mp_js.init_python(64 * 1024);
107107
await mp_js.do_str(`
108-
108+
109109
import js
110-
111-
#This function executes every line one by one and await promise if it returns a promise
110+
111+
#This function executes every line but exit the event loop if wait function is called and resumes after it resolve
112112
exec("""
113-
114-
require = JS('require')
115-
fetch = require('node-fetch') #Or do JS('window.fetch') on browser
113+
114+
fetch = False
115+
if isbrowser:
116+
fetch = JS('fetch')
117+
else:
118+
require = JS('require')
119+
fetch = require('node-fetch')
116120
response = fetch('https://github.com')
117-
response = wait(response) #This is the 'await' equivalent
121+
response = wait(response)
118122
result = response.text()
119123
result = wait(result)
120-
print(result) #Print the resulting HTML
121-
124+
print(result)
125+
122126
""")
123127
`);
124128
})();

index.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ global.mpjsPrintStdout = stdout_print;
1818
const mp = require('./lib/micropython.js');
1919
if (typeof window === 'undefined' && typeof importScripts === 'undefined') {
2020
browser = false;
21-
pyjs = require('fs').readFileSync('./js.py', {pwd: __dirname});
21+
pyjs = require('fs').readFileSync(__dirname + '/js.py').toString();
2222
}
2323
else {
2424
pyjs = require('!raw-loader!./js.py');
@@ -44,6 +44,8 @@ if (browser) {
4444

4545
global.AsyncFunction = (async () => {}).constructor;
4646

47+
let python_browser;
48+
4749
module.exports = (async () => {
4850
await wait_exist(() => global.mp_js_init);
4951
const methods = {}
@@ -53,10 +55,10 @@ module.exports = (async () => {
5355
const codes = code.split('\n');
5456
let spaces = '';
5557
for (let line of codes) {
56-
if (!line) continue;
58+
if (!line || !line.match(/[a-z]/i)) continue;
5759
let index = 0;
5860
for (let word of line) {
59-
if (index === 0 && word !== ' ') break;
61+
if (index === 0 && word.match(/[a-z]/i)) break;
6062
if (word === ' ') spaces += ' ';
6163
index += 1;
6264
}
@@ -72,16 +74,26 @@ module.exports = (async () => {
7274
}
7375
if (concurrent) {
7476
const result = [];
77+
let code_cache = [];
7578
for (var each of new_code) {
7679
let await_code;
7780
if (each.indexOf(' = wait(') > -1) {
81+
if (code_cache.length > 0) {
82+
result.push(await global.mp_js_do_str(code_cache.join('\n'), false));
83+
code_cache = [];
84+
}
7885
const [variable, wait] = each.split(' = ')
7986
const promise = wait.slice(5, -1);
8087
await_code = variable + ' = ' + promise + '._value';
8188
}
89+
else {
90+
code_cache.push(each);
91+
continue;
92+
}
8293
result.push(await global.mp_js_do_str(each, false));
8394
if (await_code) await global.mp_js_do_str(await_code, false);
8495
}
96+
if (code_cache.length > 0) result.push(await global.mp_js_do_str(code_cache.join('\n'), false));
8597
return result.join('\n');
8698
}
8799
code = new_code.join('\n');
@@ -96,6 +108,13 @@ module.exports = (async () => {
96108
}
97109
methods.init_python = async (stack) => {
98110
methods.init(stack);
111+
if (!python_browser) {
112+
await methods.do_str(`
113+
import json
114+
isbrowser = json.loads('${browser}')
115+
`);
116+
python_browser = true;
117+
}
99118
return await methods.do_str(pyjs);
100119
}
101120
global.mp_js_do_str = methods.do_str;

js.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def __getattr__(self, key):
8585
name = self._name + '.' + key
8686
js_exec("""
8787
let object = {0};
88-
if (object.constructor === Promise) {
88+
if (object && object.constructor === Promise) {
8989
await global.mp_js_do_str(`
9090
import js
9191
objcache['{0}'] = JSPromise('{0}')
@@ -97,7 +97,7 @@ def __getattr__(self, key):
9797
if (object && object.constructor === Object) for (let key in Object.keys(object)) {
9898
if (object.indexOf(key) < 0) throw Error('Not a JSON');
9999
}
100-
else if (object && object.constructor === Function || (object && object.constructor && object.constructor.name === 'AsyncFunction')) {
100+
else if (object && (object.constructor === Function || object.constructor === AsyncFunction)) {
101101
delete global.mpjscache['{0}'];
102102
return global.mp_js_do_str(`
103103
import js
@@ -141,7 +141,7 @@ def function(*args):
141141
}
142142
//object = object(...{1});
143143
global.mpjscache['{0}'] = object;
144-
if (object.constructor === Promise) {
144+
if (object && object.constructor === Promise) {
145145
await global.mp_js_do_str(`
146146
import js
147147
funcache['{0}'] = JSPromise('{0}')
@@ -154,7 +154,7 @@ def function(*args):
154154
if (object && object.constructor === Object) for (let key in Object.keys(object)) {
155155
if (object.indexOf(key) < 0) throw Error('Not a JSON');
156156
}
157-
else if (object.constructor === Function || (object.constructor && object.constructor.name === 'AsyncFunction')) {
157+
else if (object && (object.constructor === Function || object.constructor === AsyncFunction)) {
158158
return global.mp_js_do_str(`
159159
import js
160160
resolve(funcache, '{0}', JSFunction('{0}'))
@@ -180,7 +180,7 @@ def function(*args):
180180
def JS(variable):
181181
js_exec("""
182182
let object = {0};
183-
if (object.constructor === Promise) {
183+
if (object && object.constructor === Promise) {
184184
await global.mp_js_do_str(`
185185
import js
186186
objcache['{0}'] = JSPromise('{0}')

0 commit comments

Comments
 (0)