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)

 

posted @   hello_bao  阅读(372)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示