I wrote the below code to invoke python code from Javascript code, i.e on press of some button, But when I run this, I get the full python file as output instead of execution of that file. Can someone guide me how to fix that.
Got a similar question here, but could not understand the solution : Triggering Python script using AJAX Javascript request on local server using vanilla JS
My code :
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
alert("hello from js");
}
};
xhttp.open("GET", "uploadFile.py");
xhttp.send();
Can someone please help me ?
Regards
-
Do I need to make my machine a local server running Python on some port ? DO i need to run my that particular script at that port or just python .. I'am very new to server side actually and hence my questions may be very basic .. please bear with me ..lotus airtel300– lotus airtel3002021年06月20日 11:43:48 +00:00Commented Jun 20, 2021 at 11:43
-
you can send data to python from JS and receive back but what do you want to accomplish from that . for proper use you have to use some framework like Flask or Django. running basic http server won't help because making GET or POST request become hard.gaurav– gaurav2021年06月20日 11:48:37 +00:00Commented Jun 20, 2021 at 11:48
1 Answer 1
It seems that the thread that you were referencing did not name the question properly, and thus you mistook that the NodeJS process can run python scripts.
This is also assuming that you want to run the python script on your nodeJS process and not on the browser, as the browser's javascript engine would not know what to do with a .py file.
The NodeJS process cannot execute python scripts, however the python3 (assuming it is installed on your server/environment) can. So the only way to do is to get NodeJS to tell the shell environment to get python3 to run the python script.
Referencing https://stackoverflow.com/a/52575123/4036876, one of the ways you can achieve it is by using execSync or exec to run a main.py via python3:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('python3 main.py', { encoding: 'utf-8' }); // the default is 'buffer'
console.log('Output was:\n', output);