从AJAX或JQuery的运行Python脚本 [英] Run Python script from AJAX or JQuery

查看:1245
本文介绍了从AJAX或JQuery的运行Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个条件,从javascipt的运行Python脚本。我们有一个输入字符串传递给python脚本作为参数,并显示蟒蛇输出到我们的网页。

We have a requirement to run python scripts from javascipt. We have to pass an input String to the python script as an argument, and display the python output onto our web page.

下面是Python code,这code正常工作,当我运行这在我的Linux机器:./sample.py 12345,给人输出12345和./sample.py将显示没有发现的说法

Here is the Python code, this code works fine when I run this in my linux box: ./sample.py 12345, gives the output "12345" and ./sample.py would display "no argument found"

#!/usr/bin/env python

import os
import sys

if len(sys.argv) > 1:
  output = sys.argv[1]
else:
  output = "no argument found"

print "Hello World!!!"
print output

如何访问从上面蟒蛇Ajax调用的'参数',并使用该值作为参数?

How do I access the 'param' from the ajax call in above python, and use that value as an argument?

JavaScript的:

Javascript:

$.ajax({
        type: 'POST',
        url: "scripts/sample.py",
        data: {param: xyz}, //passing some input here
        dataType: "text",
        success: function(response){
           output = response;
           alert(output);
   }
}).done(function(data){
    console.log(data);
    alert(data);
});

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

修改

作为建议,我试图让我的code。使用CGI的工作。

As suggested, I am trying to get my code working using CGI.

#!/Python34/python

# Import modules for CGI handling 
import cgi, cgitb

# Create instance of FieldStorage 
data= cgi.FieldStorage()

# Get data from fields
output = data["param"]

# This will print to stdout for testing
print("Hello World!!!")
print(output)

每当Ajax调用运行时,回应是​​:[对象HTMLDivElement],当萤火虫打开显示python脚本的全部文本。我在想什么吗?请大家帮帮忙。

Whenever the Ajax call is run, response is: [object HTMLDivElement], when opened in Firebug displays the entire text of the python script. What am I missing here? Please help.

推荐答案

您Ajax调用将是一个Web请求(HTTP)的python脚本,让你的Python脚本需要的端口这样的请求在倾听和回应回去。

Your Ajax call will be a web request (http) to the python script, so your python script needs to listen on the port for such requests and respond back.

上述方法建议,用简单的 Web服务器样品内,PY或者你可以使用现有的如瓶(或其他许多人)。

Above mentioned method is recommended, to use simple web server inside your sample ,py or you can use an existing ones such as Flask (or many others).

仅供参考 - 为您简单的任务,我不会推荐Django的(它是一个又大又重的web框架,有很多的钟声你不需要)

FYI - for your simple task I would not recommend Django (its a big and heavy web framework with lots of bells you do not need).

这篇关于从AJAX或JQuery的运行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆