在python中运行js代码的几个类库execjs,PyV8,js2py

在python中运行js代码的几个类库execjs,PyV8,js2py

在python中运行js代码的几个类库execjs,PyV8,js2py

今天主要介绍python运行JS的类库:execjs,PyV8,js2py

一、execjs

一个比较好用且容易上手的类库(支持py2,与py3),支持 JS runtime。

pip install PyExecJS
或
easy_install PyExecJS

先看一下官方的例子

>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> ctx = execjs.compile("""
...     function add(x, y) {
...         return x + y;
...     }
... """)
>>> ctx.call("add", 1, 2)
3

二、PyV8

安装:python3不支持pip, 需要在这里下载对应系统的二进制文件:https://github.com/emmetio/pyv8-binaries ,然后解压后将 PyV8.py 与 _PyV8.so (如so不是这个名字需要改成这样) 两文件复制到 Python 的 site-packages 目录下,如 /usr/local/lib/python3.6/site-packages 或 /home/hlfyy/.virtualenvs/py3_scrapy/lib/python3.5/site-packages
注:该链接中,python3的暂无mac版的二进制文件
使用:

import PyV8
with PyV8.JSContext() as ctx:
	ctx.eval("""
	    var sign = 'aa'
	    function add(x, y) {
	      return x + y;
	    }
	""")
	ctx.locals.add(1,2)

三、js2py

pip install js2py

import js2py
context = js2py.EvalJs()
context.t = 'ddd'
context.execute("""
    var sign = t
    function add(x, y) {
      return x + y;
    }
""")
sign = context.sign
res = context.add(1, 2)

四、总结

使用时,一般先使用node.js跑一边js代码,没问题再使用js2py来执行,如果执行失败,再使用pyexecjs来执行,PyV8用的比较少
安装pyv8后,pyexecjs默认会使用pyv8运行,pyexecjs支持的运行时及优先级如下
First-class support (runtime class is provided and tested)
PyV8 - A python wrapper for Google V8 engine,
Node.js
PhantomJS
Nashorn - Included with Oracle Java 8

Second-class support (runtime class is privided but not tested)
Apple JavaScriptCore - Included with Mac OS X
Microsoft Windows Script Host (JScript)
SlimerJS
Mozilla SpiderMonkey

{{collectdata}}

网友评论0