Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to call js code in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how to call js code in python, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Pyexecjs

Basic use of pip install pyexecjs

First check whether the engine used is node.js.

Import execjsprint (execjs.get () .name) run result: Node.js (V8) runs js code

There are two ways for pyexecjs to run js code

1. Eval ()

Eval () can execute js code directly

Import execjsprint (execjs.eval ("a = new Array (1,2,3)")) running result: [1,2,3]

2. Compile ()

If there is a large amount of code, it is recommended to use this method. First, write the js code to a file, and then read and execute it when needed.

Create a js_text.js file and write the following code:

Function a (str) {return str;}

Python Code:

Import execjswith open ('js_text.js',' ritual, encoding='utf-8') as f: jstext = f.read () ctx = execjs.compile (jstext) a = '123456'result = ctx.call (' ajar, a) print (result) run result: 123456

First call compile to compile the js code, and then call the call method to execute. The name of the function in the js code of the first parameter of call, and the second parameter is the parameter needed by the function (if there are multiple parameters, just write down a parameter by comma).

Common problems

The string returned by the js code may make an error if it has special characters.

The solution is to base64 encode the string before returning it.

Function a (str) {return new Buffer (str) .toString ("base64");} the above is how to call js code in python. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report