用Python执行js文件代码并获取返回结果
js代码(myjs.js):
/* * @Title: This is a file for …… * @Author: JackieZheng * @Date: 2022-04-12 09:24:13 * @LastEditTime: 2022-04-12 09:40:55 * @LastEditors: Please set LastEditors * @Description: * @FilePath: myjs.js */function hello(name, word) { console.log(word, name)}let para_name = process.argv[2] ?? 'Jackie'let para_word = process.argv[3] ?? 'Hello'hello(para_name, para_word)
python代码:
"""Title: python run jsAuthor: JackieZhengDate: 2022-04-12 9:08:50LastEditTime: 2022-04-12 09:38:12LastEditors: Please set LastEditorsDescription:FilePath: runjs.py"""# -*- coding: utf-8 -*-import os# 执行node 运行myjs.js文件 后边依次是要传递的参数 2,3,4……command = os.popen("node myjs 杰克老师 您好")# print(command.read()) 防止乱码建议用下边的方式result = command.buffer.read().decode("utf-8")command.close()print(result)
运行结果:
E:\mini code\ (master -> origin) (cryptojs@1.0.0) λ python -u "e:\mini code\runjs.py"您好 杰克老师