Incorporating Python Script with Input and Output into a JavaScript Website

Question:

I’m adding extra functionality to an existing JS website, and Python works best to do the math that the program needs to do. What I need is for a user to submit information, which should then become input for my Python code, which runs and sends the output back to the site. I’m attempting to do this with an AJAX call, although I’m open to other options. What I can’t figure out is what needs to happen to or around my Python code for it to accept input and send output. I’m missing the piece that would be running, ready to accept the AJAX call, run the Python, and send everything back. I’ve looked everywhere, and I saw a couple of (not very good) examples using CGI and such. Is that the best option? What would be the cleanest and simplest way to do this?

Asked By: lala

||

Answers:

You’ll need a web server running. There are full-python web servers out there or you could make your own python code act as a server. Or you could use a PHP server and execute the python script with it, but if you’ve never done PHP I don’t think it’ll be advantageous.

EDIT:

I’d probably use the php exec function instead, as you can pass it an array.

<?PHP
$output = [];
exec("python myScript.py", $output);
// the $output array now contains all lines printed by the python script
?>

<p>
  The solution was <?PHP echo $output[0]; ?>.
</p>
Answered By: Domino
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.