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}