简体   繁体   English

从python调用外部javascript函数

[英]call an external javascript function from python

I have a javascript function that I can call with input and that returns a result. 我有一个javascript函数,我可以使用输入调用,并返回一个结果。 I can integrate this javascript function into an html-document (of course). 我可以将这个javascript函数集成到一个html文档中(当然)。

Now I would like to call exactly this javascript function from python. 现在我想从python中调用这个javascript函数。 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. 我有一个python程序,并希望通过调用python函数调用传递给JS函数的输入参数的javascript函数。 And the JS function shall return some result to python. 并且JS函数应该将一些结果返回给python。

This JS function has quite complex functionality and is used in a web project also. 这个JS函数具有相当复杂的功能,也可用于Web项目。 I would like to use same functionality in Python. 我想在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. Python是非常庞大的,所以我认为我只是找不到所需的python模块,直到知道。 I spent 2 days in searching a possibility. 我花了两天时间寻找可能性。

Thanks! 谢谢!

pyv8 will let you use the V8 JS engine from Python. pyv8将允许您使用Python的V8 JS引擎。

If the JavaScript function depends on things that are not core JavaScript (such as DOM) then you will need to find implementations of those. 如果JavaScript函数依赖于不是核心JavaScript的东西(例如DOM),那么您将需要找到那些的实现。

I had similar requirement recently and solved via node. 我最近有类似的要求,并通过节点解决。

parser.js 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 caller.py

import subprocess

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM