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)



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

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.


Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();"GET", "" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);

You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).

  1. Install python and create a sample file

    import sys
    # print sys.argv[0] prints
    # print sys.argv[1] prints your_var_1
    def hello():
        print "Hi" + " " + sys.argv[1]
    if __name__ == "__main__":
  2. Create a method in your Web API Server

    public string SayHi(string id)
        string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "";          
        Process p = new Process();
        p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName + " " + id)
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        return p.StandardOutput.ReadToEnd();                  
  3. And now for your JavaScript:

    function processSayingHi() {          
       var your_param = 'abc';
           url: '/api/your_controller_name/SayHi/' + your_param,
           type: 'GET',
           success: function (response) {
           error: function (error) {

Remember that your .py file won't run on your user's computer, but instead on the server.


Communicating through processes


Python: This python code block should return random temperatures.


import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.