Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JavaScript and Python work together?

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.

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:

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!

like image 413
Karan Dhir Avatar asked Nov 16 '17 12:11

Karan Dhir


2 Answers

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.

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

like image 167
Mads Marquart Avatar answered Oct 30 '22 04:10

Mads Marquart


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:

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

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

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

like image 28
Imre_G Avatar answered Oct 30 '22 06:10

Imre_G