Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to call js code in python

Shulou Source: shulou.com Published: 2022-06-02 07:14:10 09月25日 Update

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.

Tags: Code parameters runs methods characters results functions strings that is files more knowledge articles first practical special multiple work meetings common engines Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux vpn Apple MySQL Redmi