Python3 調用 js 函數

PyExecJS

#encoding: utf-8
#author: walker
# date: 2019-03-13
# summary: 利用 PyExecJS 調用 js 函數

import execjs

JSCode = r'''
            function add(x, y) {
                return x + y;
            }
'''
CTX = execjs.compile(JSCode)

def test():
    # 直接使用
    print(execjs.get().eval('3+2'))

    # 調函數使用
    print(CTX.call('add', 3, 6))

if __name__ == '__main__':
    test()


【Node.js】

#encoding: utf-8
#author: walker
# date: 2019-03-13
# summary: 直接用 Node.js 調用 js 函數

from subprocess import check_output

def test():
    # 直接調用
    bytesTxt = check_output('node -e console.log(3+2)', timeout=100)
    print(bytesTxt.decode('utf8').strip())
    
    # 用 node 直接執行 js 腳本
    bytesTxt = check_output(['node','t.js', '3', '6'], timeout=100)
    print(bytesTxt.decode('utf8').strip())


if __name__ == '__main__':
    test()
  • t.js

function add(x, y) {
    return x + y;
}

var args = process.argv.splice(2);
console.log(add(parseInt(args[0]), parseInt(args[1])));


*** walker ***

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章