简体   繁体   中英

How to get a return variable from a Python Script through JQuery?

Currently I am trying to call a simple python script to test if I can receive output into my javascript function. However, when I do this ajax request

 function testPhy()
        {
            $.ajax({
              url: "./Phython/test.py",
              data: {param: text},
              success: function(dataR){
                  console.log("LK: " + dataR)
              },
              error: function(request, status, error) { 
              console.log("Error: " + error) 
              }
            });
        }


        testPhy();

I get the content's of the script and not the return variable

print("script running")
text = "Why hi there"
return text

Is there a way I can grab the contents of text from the python file using this Ajax query?

You need to create Server Node.js for example, i suggest you to read this tutorial

1- you create a basic server with a basic client web

2- use "child_process" package which comes packaged with node.

 const spawnpy = require("child_process").spawn;
 const pythonProcess = spawnpy('python',["path/script.py", arg1, arg2,  .and so on]);

3- To send data to node just do that in the python script:

     print(dataToSendToNode)
     sys.stdout.flush()

4- node server can listen for data using:

   pythonProcess.stdout.on('data', (data) => {
      // Do something with the data returned from python script
   });

5- you answer to the ajax request (send data to your client browser)

You have lot of solutions to execute a python script with node.js, you could use python-shell, so when your server will be activa, search on google python node.js ...

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