如何让 JavaScript 和 Python 协同工作?

Kar*_*hir 5 javascript python jquery python-3.x

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

考虑这个例子:

阅读评论以了解模型!

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>';
  })



};
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

Mad*_*art 5

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

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