Python3引入v8引擎执行js代码

安装

下载文件,解压后得到.whl文件,然后使用pip安装.whl。pip安装whl如果不懂自行百度。https://www.aliyundrive.com/s/Dcn5FHg44a4

注:此whl文件适用于Python3引用v8引擎,如需得到其他Python版本的whl文件,请移步网站https://github.com/sqreen/PyMiniRacer 自行构建whl文件。
在这里插入图片描述

使用

1.安装好.whl后,即可成功引入v8环境:from py_mini_racer import MiniRacer

2.创建对象 MiniRacer() ,使用eval或call即可执行js代码。下面是一些简单的例子。

Examples
MiniRacer is straightforward to use:

>>> from py_mini_racer import MiniRacer
>>> ctx = MiniRacer()
>>> ctx.eval("1+1")
2
>>> ctx.eval("var x = {company: 'Sqreen'}; x.company")
'Sqreen'
>>> print(ctx.eval("'\N{HEAVY BLACK HEART}'"))>>> ctx.eval("var fun = () => ({ foo: 1 });")
Variables are kept inside of a context:

>>> ctx.eval("x.company")
'Sqreen'
While eval only supports returning primitive data types such as strings, call supports returning composite types such as objects:

>>> ctx.call("fun")
{'foo': 1}
Composite values are serialized using JSON. Use a custom JSON encoder when sending non-JSON encodable parameters:

import json

from datetime import datetime

class CustomEncoder(json.JSONEncoder):

        def default(self, obj):
            if isinstance(obj, datetime):
                return obj.isoformat()

            return json.JSONEncoder.default(self, obj)
>>> ctx.eval("var f = function(args) { return args; }")
>>> ctx.call("f", datetime.now(), encoder=CustomEncoder)
'2017-03-31T16:51:02.474118'
MiniRacer is ES6 capable:

>>> ctx.execute("[1,2,3].includes(5)")
False
V8 heap information can be retrieved:

>>> ctx.heap_stats()
{'total_physical_size': 1613896,
 'used_heap_size': 1512520,
 'total_heap_size': 3997696,
 'total_heap_size_executable': 3145728,
 'heap_size_limit': 1501560832}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐