5
5
funcache = {}
6
6
procache = {}
7
7
8
+ #Javascript's JSON Types for eliminating json.loads
9
+ true = True
10
+ false = False
11
+ null = None
12
+ undefined = None
13
+
8
14
def js_exec (code , * args ):
9
15
code = format (code , * args )
10
16
return js .exec ('(async () => {\n ' + code + '\n })();' )
@@ -24,24 +30,22 @@ def format(string, *args):
24
30
25
31
def wait (promise ):
26
32
procache [promise ._name ] = promise
27
- #js.exec('console.log("function")')
28
- js .exec ("""
29
- //console.log('exec');
33
+ js_exec ("""
30
34
global.promiseWaitInterval = setInterval(() => {
31
- //console.log('interval')
32
35
const object = global.mpjscache['{0}'];
33
- console.log(object)
36
+ // console.log(object)
34
37
if (object && object.constructor !== Promise) {
35
38
clearInterval(global.promiseWaitInterval);
36
39
global.promiseWaitInterval = undefined;
37
40
global.mp_js_do_str(`
38
41
import js
39
42
procache['{0}']._resolved = True
43
+ procache['{0}']._value = JS('global.mpjscache["{0}"]')
40
44
procache['{0}'] = procache['{0}']._value
41
45
`);
42
46
}
43
47
}, 500);
44
- """ . replace ( '{0}' , promise ._name ) )
48
+ """ , promise ._name )
45
49
exit
46
50
47
51
def resolve (cache , name , value ):
@@ -51,6 +55,20 @@ def resolve(cache, name, value):
51
55
else :
52
56
cache [name ] = value
53
57
58
+ async_id = 0
59
+
60
+ def async_py (function ):
61
+ def wrap (** kwargs ):
62
+ code_string = function (** kwargs )
63
+ for key in kwargs :
64
+ if key not in code_string : continue
65
+ async_id += 1
66
+ asycache [async_id ] = kwargs [key ]
67
+ code_string = code_string .replace (key , 'asycache[%s]' % (async_id ))
68
+ exec (code_string )
69
+ exit
70
+ return wrap
71
+
54
72
class JSPromise ():
55
73
56
74
def __init__ (self , name ):
@@ -69,9 +87,13 @@ def __init__(self, name):
69
87
self ._name = name
70
88
71
89
def __len__ (self ):
72
- return 1
90
+ if self ._name :
91
+ return 1
92
+ else :
93
+ return 0
73
94
74
95
def __dir__ (self ):
96
+ if not self ._name : return []
75
97
js_exec ("""
76
98
let keys = JSON.stringify(Object.keys({0}));
77
99
global.mp_js_do_str(`
@@ -82,7 +104,7 @@ def __dir__(self):
82
104
return dircache .get (self ._name , [])
83
105
84
106
def __getattr__ (self , key ):
85
- name = self ._name + '.' + key
107
+ name = self ._name + '.' + key if self . _name else key
86
108
js_exec ("""
87
109
let object = {0};
88
110
if (object && object.constructor === Promise) {
@@ -108,7 +130,7 @@ def __getattr__(self, key):
108
130
return global.mp_js_do_str(`
109
131
import js
110
132
import json
111
- resolve(objcache, '{0}', json.loads(''' ${object}''') )
133
+ resolve(objcache, '{0}', ${object})
112
134
`);
113
135
}
114
136
catch(error) {
@@ -121,6 +143,7 @@ def __getattr__(self, key):
121
143
return objcache .get (name )
122
144
123
145
def __setattr__ (self , key , value ):
146
+ if not self ._name : return
124
147
value = json .dumps (value )
125
148
object_name = self ._name + '.' + key
126
149
js_exec ("""
@@ -164,7 +187,7 @@ def function(*args):
164
187
return global.mp_js_do_str(`
165
188
import js
166
189
import json
167
- resolve(funcache, '{0}', json.loads(''' ${object}''') )
190
+ resolve(funcache, '{0}', ${object})
168
191
`);
169
192
}
170
193
catch(error) {
@@ -178,56 +201,22 @@ def function(*args):
178
201
return function
179
202
180
203
def JS (variable ):
181
- js_exec ("""
182
- let object = {0};
183
- if (object && object.constructor === Promise) {
184
- await global.mp_js_do_str(`
185
- import js
186
- objcache['{0}'] = JSPromise('{0}')
187
- `)
188
- object = await object;
189
- }
190
- try {
191
- if (object && [Array, Object, Number, String, Boolean, Function, AsyncFunction].indexOf(object.constructor) < 0) throw Error('Not JSON Serializable');
192
- if (object && object.constructor === Object) for (let key in Object.keys({0})) {
193
- if (object.indexOf(value) < 0) throw Error('Not a JSON');
194
- }
195
- else if (object && (object.constructor === Function || object.constructor === AsyncFunction)) {
196
- delete global.mpjscache['{0}'];
197
- return global.mp_js_do_str(`
198
- import js
199
- resolve(objcache, '{0}', JSFunction('{0}'))
200
- `);
201
- }
202
- object = object !== undefined ? JSON.stringify(object) : 'null';
203
- return global.mp_js_do_str(`
204
- import js
205
- import json
206
- resolve(objcache, '{0}', json.loads('''${object}'''))
207
- `);
208
- }
209
- catch(error) {
210
- return global.mp_js_do_str(`
211
- import js
212
- resolve(objcache, '{0}', JSObject('{0}'))
213
- `);
214
- }
215
- """ , variable )
216
- return objcache .get (variable )
204
+ empty = JSObject ('' )
205
+ return getattr (empty , variable )
217
206
218
207
#require = JS('require')
219
208
#result = require('fs').readFileSync('./test.js').toString()
220
209
#print(result)
221
210
222
211
#This code block is adaptable to Javascript's event loop
223
- #exec("""
212
+ async {
224
213
225
- # require = JS('require')
226
- # response = require('node-fetch')('https://github.com/')
227
- # response = wait( response)
228
- # print(response)
229
- # result = response.text()
230
- # result = wait( result)
231
- # print(result)
214
+ require = JS ('require' )
215
+ response = require ('node-fetch' )('https://github.com/' )
216
+ response = await response
217
+ print (response )
218
+ result = response .text ()
219
+ result = await result
220
+ print (result )
232
221
233
- #""" )
222
+ } async ( )
0 commit comments