Python3调用js函数

【PyExecJS】

阜宁ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!

#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])));

【Node.js 指定函数】

#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()

【相关阅读】

  • Python之系统交互(subprocess)

*** walker ***

网站栏目:Python3调用js函数
文章出自:https://www.cdcxhl.com/article34/joopse.html

成都网站建设公司_创新互联,为您提供定制网站网站维护全网营销推广网站导航品牌网站设计软件开发

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

绵阳服务器托管