Call Python function from JavaScript code


I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want. Is this possible? Could you adjust the below snippet to work?

JavaScript code:

var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;
// Here I would like to call the Python interpreter with Python function
arrOfStrings = openSomehowPythonInterpreter("~/", "processParagraph(text)");

~/ contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:

import nltk # is not in JavaScript
def processParagraph(text):
  nltk calls
  return lst # returns a list of strings (will be converted to JavaScript array)
5/31/2019 2:52:13 AM

Accepted Answer

All you need is to make an ajax request to your pythoncode. You can do this with jquery, or use just javascript

  type: "POST",
  url: "~/",
  data: { param: text}
}).done(function( o ) {
   // do something
11/1/2012 11:01:48 AM

From the document.getElementsByTagName I guess you are running the javascript in a browser.

The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.

For example, using jQuery you can do something like:

    function(data, textStatus, jqXHR) {

You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.

A typical implementation looks like:

def my_webservice():
    return jsonify(result=some_function(**request.args)) 

You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow