开发者

call an external javascript function from python

开发者 https://www.devze.com 2023-03-06 11:11 出处:网络
I have a javascript function that I can call with input and that returns a result. I can integrate this javascript function into an html-document (of course).

I have a javascript function that I can call with input and that returns a result. I can integrate this javascript function into an html-document (of course).

Now I would like to call exactly this javascript function from python. I have a python programm and want to call the javascript function with input parameters passed to the JS function by the calling python function. And the JS function shall return some result to python.

This JS function has quite complex functionality and is used in a web project also. I would like to use same functionality in Python.

Does anyone know how to solve this? Python is quite huge so I think I only did not find the required python module up until know. I s开发者_开发百科pent 2 days in searching a possibility.

Thanks!


pyv8 will let you use the V8 JS engine from Python.

If the JavaScript function depends on things that are not core JavaScript (such as DOM) then you will need to find implementations of those.


I had similar requirement recently and solved via node.

parser.js

module.exports = {decode};  // entry for node

function decode(payload) {
  var decoded = {};
  // ...
  console.log(JSON.stringify(decoded));
  return decoded;
}

terminal

node -e 'require("./parser.js").decode("foobar")'

output: the parsed data

caller.py

import subprocess

cmd = """node -e 'require(\"./parser.js\").decode(\"{}\")'"""
output = subprocess.check_output(cmd.format(data), shell=True)
0

精彩评论

暂无评论...
验证码 换一张
取 消