大家好,我是ConardLi。
最近在Github上发现一个非常有意思的项目PythonMonkey,它可以让我们直接在JavaScript中运行Python代码,也可以在Python中运行JavaScript和WebAssembly代码,而且几乎没有性能损失。
PythonMonkey是一个Python库,它使用Mozilla的SpiderMonkeyJavaScript引擎构建,可以实现Python和JavaScript之间的互操作。它可以让JavaScript库能够在Python代码中无缝使用,反之亦然,而不会造成比较大的性能损失。例如,我们可以从JavaScript库中调用NumPy等Python包,或者直接从Python中使用crypto-js等 NPM 包。此外,使用WebAssembly API和SpiderMonkey引擎在Python中执行WebAssembly模块也变得非常简单。开发者也可以使用PythonMonkey重构用Python编写的代码改为在 JS 中执行,利用SpiderMonkey的即时编译器获得接近原生的速度。
PythonMonkey还附带了PMJS,这是一个类似于Node.js的JavaScript运行时环境,支持从JavaScript调用Python库。
下面是一个简单的 “hello world”示例,演示了从JavaScript生成的字符串并返回到Python上下文:
importpythonmonkeyaspm>>>hello = pm.eval(" 'Hello World'.toUpperCase(); ")>>>print(hello)'HELLO WORLD'下面是一个复杂一点的示例,演示了将Python print函数作为参数传递给JavaScript函数,然后从Python调用该JavaScript函数:
importpythonmonkeyaspm>>> hello = pm.eval("(func) => { func('Hello World!')}")>>> hello(print)Hello World!通过下面的写法我们可以直接在JavaScript代码中使用Python的print函数:
constpyPrint = python.eval("print");pyPrint("Hello, World!");// this outputs "Hello, World!"我觉得一个比较实用的应用场景就是我们可以轻松地将一个JavaScript库移植到Python,而不需要承受使用Python重写库和维护迁移的巨大成本。JavaScript比Python处理异步代码的能力要好很多。我们只需要做下面这样简单的操作:
my-javascript-module.js
exports.sayHello =()=>{console.log('hello, world') };main.py
importpythonmonkeyaspmtest = pm.require('./my-javascript-module');test.sayHello()# this prints hello, world同样的,我们可以从JavaScript中通过CommonJS加载一个Python模块:
my-python-module.py
defgetStringLength(s):returnlen(s)exports['getStringLength'] = getStringLengthmy-javascript-module.js
const{ getStringLength } =require('./my-python-module');functionprintStringLength(s){console.log(String: "${s}" has a length of${getStringLength(s)});}module.exports = { printStringLength, };main.py
importpythonmonkeyaspmtest = pm.require('./my-javascript-module');test.printStringLength("Hello, world!")# String: "Hello, world!" has a length of 13PythonMonkey还利用了一些其他的SpiderMonkey功能,例如它的WebAssembly(WASM) 引擎,它可以允许Python在沙箱中运行来自各种语言(例如C、C++、Rust等)的不受信任的WASM代码。
在 Python 中调用 WebAssembly 函数:
importasyncioimportpythonmonkeyaspmasyncdefasync_fn():# read the factorial.wasm binary filefile = open('factorial.wasm','rb')wasm_bytes = bytearray(file.read())# instantiate the WebAssembly codeWebAssembly = pm.eval('WebAssembly')wasm_fact =awaitWebAssembly.instantiate(wasm_bytes, {})# return the "fac" factorial function from the wasm modulereturnwasm_fact.instance.exports.fac;# await the promise which returns the factorial WebAssembly functionfactorial = asyncio.run(async_fn())# execute WebAssembly code in Python!print(factorial(4))# this outputs "24.0" since factorial(4) == 24print(factorial(5))# this outputs "120.0"print(factorial(6))# this outputs "720.0"还有更多的示例,我们可以查看 Github 上的例子:https://github.com/Distributive-Network/PythonMonkey-examples
目前已经有几个用于在Python中运行JavaScript的项目了,例如JS2PY、PyV8和Metacall。
JS2Py完全用Python实现,它消除了对V8或SpiderMonkey等大型引擎的需求。但是这种方法也有一些问题,如果不利用现有的JavaScript引擎,JS2Py就无法从V8或SpiderMonkey等引擎在数百万人每天使用的浏览器中提供的强大、不断更新且经过验证的代码库中受益。此外,JS2Py还缺少WASM引擎、对最新JavaScript规范 (ECMA-262) 的支持以及这些引擎内置的强大JIT等功能。现代异步JS编程中广泛使用的JavaScript Promises和Async/Await在JS2Py中也是缺失的,但在PythonMonkey中是可用的。使用Python编写,JS2Py面临SpiderMonkey中不存在的性能限制;在SunSpider JavaScript基准测试报告显示:使用PythonMonkey比JS2Py快了1162.5倍。
PyV8和Cloudflare的现代实现是Google V8 JavaScript引擎绑定的Python包装器。这意味着它的运行级别比PythonMonkey更低,并且不支持事件循环功能,例如JavaScript的Promise和async/await。
Metacall是一个可扩展、可嵌入和可互操作的跨平台多语言运行时,可与多种编程语言(例如JavaScript、Python、Ruby、Rust、C#、Java等)进行互操作。但是Metacall支持的广泛支持语言也是有代价的,并且需要在Python包之外的系统上安装额外的软件才能运行。此外,Metacall会复制在Python和JavaScript之间传递的数据,而不是像PythonMonkey那样通过引用传递,从而导致性能影响。
虽然替代项目与PythonMonkey的模型有相似之处,但它们达不到PythonMonkey提出的互操作性、易用性和速度。
最后
参考:https://github.com/Distributive-Network/PythonMonkey/
大家觉得这个项目如何呢?欢迎在评论区留言。
如果你想加入高质量前端交流群,或者你有任何其他事情想和我交流也可以添加我的个人微信ConardLi。
点赞和在看是最大的支持⬇️❤️⬇️