python调用js之execjs、js2py
1.js
var Base65 = {
_0: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode: function (a) {
return a + this._0;
}
}
var Base64 = {
_0: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode: function (e) {
var t = '';
var n,
r,
i,
s,
o,
u,
a;
var f = 0;
e = Base64._2(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._0.charAt(s) + this._0.charAt(o) + this._0.charAt(u) + this._0.charAt(a)
}
return 'zM' + t + '=='
},
_2: function (e) {
e = e.replace(/rn/g, 'n');
var t = '';
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128)
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128)
}
}
return t
}
}
第一种方式:
import execjs
print(execjs.get().name)
def testJs():
with open("1.js", "r") as f:
js = execjs.compile(f.read())
res = js.eval("Base64.encode('9999')")
print(res)
res = js.call("Base65.encode", "9999")
print(res)
res = js.call("Base64.encode", "9999")
print(res)
testJs()
第二种方式:【推荐】
import js2py
content = js2py.EvalJs() # 实例化解析js对象
with open("1.js", "r") as f:
content.execute(f.read()) # js转python代码
result = content.Base64.encode("9999")
print(result)