如何让 JavaScript 和 Python 协同工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47330200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:18:22  来源:igfitidea点击:

How to make JavaScript and Python work together?

javascriptjquerypythonpython-3.x

提问by Karan Dhir

I want to make a two way communication model for JavaScript and Python. I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.

我想为 JavaScript 和 Python 制作一个双向通信模型。我希望 JavaScript 处理数据并将其发送给 Python,然后 Python 处理它并将其发送回 JavaScript。我不知道如何实现这一点以及如何进行两种语言之间的通信。

Consider the example:

考虑这个例子:

Read the comments for clarity of the model!

阅读评论以了解模型!

var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");

function fetchNames() {
  div_files.innerHTML = ""; // clears the file div
  div_results.innerHTML = ""; // clears the results div

  var checkbox_elements = document.getElementsByClassName('filename');

  Array.from(checkbox_elements).forEach(function(k) {
    if (k.checked) {

      files.push(k.value);
      div_files.innerHTML += k.value + '<br>';
    }

  });

  // the files array should now be shared with python 
  
  //console.log(files);

  // JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS

  // when the cal_array is available with JS only then it shall start processing the code mentioned below
  
  var cal_array = [
    [2231, 11640, 104621],
    [2231, 11640, 104621],
    [9, 494, 3339]
  ];
  Array.from(cal_array).forEach(function(k) {
    div_results.innerHTML += k + '<br>';
  })



};
<form>
  <input type="checkbox" class="filename" value="./first.html">First File<br>
  <input type="checkbox" class="filename" value="./second.html">Second File<br>
  <input type="checkbox" class="filename" value="./third.html">Third File<br>
  <br>
  <input type="button" value="Submit" onclick="fetchNames()">
</form>
<br>
The selected file(s) are:
<div id="files"></div>
<br> The result shows the number of lines, words, and characters of the respective files mentioned above:
<div id="results"></div>

The Python Script is as follows:

Python脚本如下:

import os

files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
 for val in files:
  file_details = []
  fname=(val)
  infile=open(fname, 'r')
  lines=0
  words=0
  characters=0
  for line in infile:
      line = line.strip(os.linesep)
      wordslist=line.split()
      lines=lines+1
      words=words+len(wordslist)
      characters=characters+ len(line)
  file_details.append(lines)
  file_details.append(words)
  file_details.append(characters)
  cal_array.append(file_details)

calculation()


print(cal_array)

# some code here to share cal_array with javascript

I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!

我是 Python 的菜鸟,但我想知道如何让这两种语言相互交互?我真的很感激任何帮助!

回答by Mads Marquart

If what you want is to create a web-app, and then send the data from there to your server via. AJAX, where you will work on the data in Python, what you need is something like Flask.

如果您想要的是创建一个网络应用程序,然后通过它将数据从那里发送到您的服务器。AJAX,您将在 Python 中处理数据,您需要的是Flask 之类的东西。

If what you want is to create a web-app that also runs the Python code, you need a python interpreter written in JavaScript, something like pyjs

如果你想要创建一个也运行 Python 代码的 web 应用程序,你需要一个用 JavaScript 编写的 Python 解释器,比如pyjs

回答by Imre_G

There are a lot of ways to do this and this is quite a broad question. Since JavaScript exists in the browser and python is run on your computer, you must set up some sort of webserver for the two to talk together. The most common and easy way is to go via the normal HTTP request response method. The most straightforward combination is Flask on the python site and AJAX on the JavasScript side. However, there are a hundred other ways to do this. I would suggest to read up on:

有很多方法可以做到这一点,这是一个相当广泛的问题。由于 JavaScript 存在于浏览器中,而 Python 运行在您的计算机上,因此您必须设置某种网络服务器让两者一起对话。最常见和最简单的方法是通过普通的 HTTP 请求响应方法。最直接的组合是 python 站点上的 Flask 和 JavaScript 端的 AJAX。但是,还有一百种其他方法可以做到这一点。我建议阅读:

REST APIs: https://www.codecademy.com/courses/javascript-beginner-en-EID4t/0/4

REST API:https: //www.codecademy.com/courses/javascript-beginner-en-EID4t/0/4

Ajax (JavaScript) https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Ajax (JavaScript) https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Flask (Python) http://flask.pocoo.org/

烧瓶 (Python) http://flask.pocoo.org/