Python中执行JS代码,通常两个库:js2py,pyexecjs
1、安装
pip install js2py
2、直接执行js代码
js2py.eval_js(str),str是js代码的Python字符串,eval_js方法将js代码直接在Python中执行;
import js2pyjs_func = """function add(a, b){return a+b}"""add = js2py.eval_js(js_func)print(add(1, 2))js2py.eval_js('console.log("hello wrold")')
3、翻译js代码
import js2py# 将js代码翻译成Python脚本print(js2py.translate_js("console.log('hello world')"))# 将js文件翻译为Python脚本js2py.translate_file('test.js', 'test.py')
4、在js代码中使用python函数
import js2pyprint("sum: ", sum([1, 2, 3]))context = js2py.EvalJs({'python_sum': sum})print("context.python_sum: ", context.python_sum)js_code = """python_sum([1,2,3])"""print("js_code运行结果: ", context.eval(js_code))
5、js代码中导入Python模块并使用
import js2py# 在js代码中导入Python模块并使用# 使用pyimport语法js_code = """pyimport requestsconsole.log('导入成功');var response = requests.get('http://www.baidu.com');console.log(response.url);console.log(response.content);"""js2py.eval_js(js_code)
6、执行js代码中的某个函数
import js2pyjs_code = """let n = 10;function test(){if(n == 10){console.log(n);}}"""js_obj = js2py.EvalJs() #实例化解析js对象js.execute(js_code) #js转python代码js.test() #调用js中的TL函数
