Make Javascript Execute a Python Script

Viewed 11517

I have a question that has been asked several times here and other places around the internet*, but answers I've seen are incomplete or ineffective.

I would like to have a JavaScript function runPy() that, upon being called (in a browser, via a button-click for instance), will execute a Python script in my server that we'll call test.py.

Let's say that test.py is simply designed to create a text file and write in it 'hello world'

Python

f = open('test.txt', 'w+')
f.write('hello world')

Based on other answers, I have pieced together the following JavaScript/jQuery function:

JavaScript

function runPy() {
    $.ajax({
        type:'POST',
        url:'test.py',
        success: function(data) {                                                     
            console.log(data)
        };
    });
}

Now, this is of course incorrect. As one might expect, rather than running the Python script, it prints to the console the contents of the script:

Console

f = open('test.txt', 'w+')
f.write('hello world')

How would I go about editing my JavaScript (and/or Python) to achieve the functionality I would like? In a perfect world, I would like to avoid importing any new dependencies (I've seen some answers dependent on Flask or Django) but of course beggars can't be choosers.

Additionally, if I will allow myself to get greedy, it would be very nice to be able to pass arguments to the Python script as well, or even use JavaScript to call a specific function in the Python script, and have the results passed back to the client-side JavaScript.

*Similar Questions
Call python function from JS
how to call python script from javascript?
Run Python scripts from JavaScript functions

1 Answers

You're going on the right path.

But, here's why the POST isn't working. Except for HTML filetype, making a POST call to fetch a static file on the server (i.e. random.js, random.css etc) will print the raw file content. In this scenario, you'll need to handle this on the server-side backend code. I don't know which backend framework you're using but here are some articles that can help you with this:

NodeJS: https://medium.com/swlh/run-python-script-from-node-js-and-send-data-to-browser-15677fcf199f

.NET: https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5

Java: Running a .py file from Java

UPDATE!!: Due to the recent developments in the space of Web Development, it is now possible to run Python on the Client-side through WebAssembly. Please find more instructions here: Pyodide

Related