前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python3 调用 js 函数

Python3 调用 js 函数

作者头像
py3study
发布2020-01-03 16:35:58
3.2K0
发布2020-01-03 16:35:58
举报
文章被收录于专栏:python3

PyExecJS

代码语言:javascript
复制
#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】

代码语言:javascript
复制
#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
代码语言:javascript
复制
function add(x, y) {
    return x + y;
}

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

【Node.js 指定函数】

代码语言:javascript
复制
#encoding: utf-8
#author: walker
# date: 2019-03-14
# summary: 直接用 Node.js 调用指定 js 函数

from subprocess import check_output

JSCode = r'''
            function add(x, y) {
                return x + y;
            }
            
            function sub(x, y) {
                return x - y;
            }
            
            function foo(x) {
                return x;
            }
'''

def test():
    jscode = JSCode + 'process.stdout.write(add(3, 2).toString())'
    rtn = check_output('node', input=jscode, universal_newlines=True, timeout=100)
    print(rtn)


if __name__ == '__main__':
    test()
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档