【问题标题】:How to get a return variable from a Python Script through JQuery?如何通过 JQuery 从 Python 脚本中获取返回变量?
【发布时间】:2021-03-11 05:29:12
【问题描述】:

目前我正在尝试调用一个简单的 python 脚本来测试我是否可以将输出接收到我的 javascript 函数中。但是,当我执行此 ajax 请求时

 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();

我得到的是脚本的内容,而不是返回变量

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

有没有办法使用这个 Ajax 查询从 python 文件中获取文本内容?

【问题讨论】:

  • 实际上服务器只是发送文件python的内容,但是你必须修改服务器以运行python进程并返回值..
  • 你的服务器是php、python、C#、js...?
  • 目前我没有运行服务器。有没有办法在没有服务器的情况下做到这一点? @法国人
  • 不,你不能这样做,因为使用客户端浏览器你不能访问本地文件(安全)
  • 那么我将如何设置基本服务器?我不需要任何复杂的东西。我只需要返回值

标签: javascript python jquery return


【解决方案1】:

例如你需要创建Server Node.js,我建议你阅读这个tutorial

1- 你创建一个带有基本客户端网络的基本服务器

2-使用node自带的“child_process”包。

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

3- 要向节点发送数据,只需在 python 脚本中执行此操作:

     print(dataToSendToNode)
     sys.stdout.flush()

4-节点服务器可以使用以下方式监听数据:

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

5- 你回答 ajax 请求(发送数据到你的客户端浏览器)

你有很多用node.js执行python脚本的解决方案,你可以使用python-shell,所以当你的服务器激活时,在google上搜索python node.js ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2016-04-18
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2016-09-02
    相关资源
    最近更新 更多