简体   繁体   中英

How to execute Python script from Javascript or Nodejs?

I am trying to use the list from my python output into a dropdown menu in an HTML form.

I have a website built in HTML/ CCS, a server with nodeJS, and several scripts i want to use in python3.

I tested multiple thngs but I can't manage to make it work.

  1. I tried putting some Javascript but I can't get the infos from the python script

  2. I tried running the script from nodeJS, but the script takes a lot of time so it doesn't work.

here is my app.js :

app.post("/getData", function (request, response) {
    var IP = request.body.IP;
    var user = request.body.user;
    var password = request.body.password;
    const testscript = exec('python getCPG.py ' + IP + user + password);
    console.log("test1");
    testscript.stdout.on('data', function (data) {
        console.log("test2");
        console.log(data);
        // sendBackInfo();
    });
    //response.sendFile(path.join(__dirname + '/public/views/indexwithIP.html'));
    //app.post("/LUNProvisionning", function (request, response) {
    //    console.log(request.body.serveur);
    //    console.log(request.body.volumetrie);
    //    console.log(request.body.type);
    //    response.sendFile(path.join(__dirname + '/public/views/index.html'));
    //});

    response.sendFile(path.join(__dirname + '/public/views/index.html'));
});

Here is my html form:

    <form action="/getData" method="post" name="getData">
        <fieldset>
            <legend>LUN Provisionning</legend>
            <label>IP baie : </label>
            <input name="IP" id="IP" required>
            <br />
            <label>user baie : </label>
            <input type="text" placeholder="3paradm" name="user" id="userbaie" required>
            <label>Password baie : </label>
            <input type="password" name="password" id="PWbaie" required>
            <br />
        </fieldset>
    </form>

This sends data to the servers which runs the python script. But the server takes too much time to get an answer. Then I will try to put the answer in a dropdown form. I had to create 2 form or else it wouldn't work using JavaSscript and putting a button.

Here is the output of my python script:

SSD_r1
SSD_r5
SSD_r6
fs_cpg
CPG4S2

edit "adding python script" Here is the python script:

from hpe3parclient import client, exceptions
import sys

IPbaie = sys.argv[1]
userbaie = sys.argv[2]
pwbaie = sys.argv[3]

cl = client.HPE3ParClient("http://" + IPbaie + ":8008/api/v1")
cl.setSSHOptions(IPbaie, userbaie, pwbaie)

def getCPG():
#retourn une liste
        temp = []
        cpg = cl.getCPGs()
        listcpg = cpg['members']
        for x in listcpg:
                temp.append(x.get('name'))
        return(temp)

try:
    cl.login(userbaie, pwbaie)
    print("login successful.")
except exceptions.HTTPUnauthorized as ex:
    print ("login failed.")
try:
    listcpg = getCPG()
    for x in listcpg:
        print (x)
except exceptions.HTTPUnauthorized as ex:
    print ("You must login first")
except Exception as ex:
    print (ex)

cl.logout()
print ("logout worked")

Thank you

How about using child_process.execFile since exec has been deprecated according to: https://www.npmjs.com/package/exec

const {execFile} = require('child_process');
const testscript = execFile('python3', ['file_name.py', 'command_line_arg1', 'command_line_arg2', 'command_line_arg3'], (error, stdout, stderr) => {
    if (error) throw error;
    console.log(stdout);
    })

This would print every print statement in your python file. So I would suggest you should remove them.

I would suggest putting an API in front of your server-python scripts. This adds a layer of abstraction between the front and backend (which is good for security). Your javascript function could call the API endpoint, and retrieve the output.

Regarding the slowness of the python script: Not sure how to help there without seeing the code.

脚本名称后似乎应该有一个空格字符:

const testscript = exec('python getCPG.py ' + IP + user + password);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM