在python中调用js或者nodejs

在python中调用js或者nodejs要使用PyExecJs第三方包。

pip 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

这是没有用到nodejs的情况;如果用到nodejs,这种写法会报“Cannot find module 'xxx'”的错误。

如果要用nodejs,要在环境变量中指定node_modules的路径。

os.environ["NODE_PATH"] = os.getcwd()+"/node_modules"

示例代码

import os
import execjs
import json

# os.environ["EXECJS_RUNTIME"] = "Node"
os.environ["NODE_PATH"] = os.getcwd()+"/node_modules"
print execjs.get().name

parser = execjs.compile("""
    var wtf_wikipedia = require("wtf_wikipedia");
    function parse(text) {
        return wtf_wikipedia.parse(text);
    }
""")

if __name__ == "__main__":
    obj = parser.call("parse", '<doc id=\'1\'></doc>')
    print obj
posted @ 2016-07-04 21:42  穆穆里  阅读(31535)  评论(0编辑  收藏  举报