如何从HTML页面调用python命令

how to call python command from html page?

本文关键字:调用 python 命令 HTML      更新时间:2023-09-26

我想从我的html页面调用python命令。

代码为:

<form class="form" action="" method="post" name="new-service" enctype=multipart/form-data>
      <div class="control-group">
          <div class="controls">
               <input id="Search" name="Search" type="text" placeholder="Search.. eg: moto g" class="form-control input-xlarge search-query center-display" required="">
   <!--  here i want to call python command  or function  -->
          </div>
     </div>
      </form>

我的python命令是:

$ python main.py -s=bow    

不能直接从UI调用命令。这是特定于后端的。但是,在处理表单的视图中,您可以执行以下操作:

from django.core.management import call_command
call_command('your_command_name', args, kwargs)

查看此处的文档页面以供参考:https://docs.djangoproject.com/en/1.8/ref/django-admin/调用命令

使用jQuery向服务器上的python脚本发送请求,该请求将作为CGI/Fast CGI脚本或通过WSGI(适用于Apache的mod_wsgi)或mod_python(适用于Apache)处理。

您的Python脚本将使用查询字符串接收输入。

客户端示例:

<html><head><title>TEST</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
pyurl = "/cgi-bin/main.py"; // Just for example. It can be anything. Doesn't need to be Python at all
function callpy (argdict) {
    $.post(pyurl, argdict, function (data) {    
    // Here comes whatever you'll do with the Python's output.
    // For example:
    document.write(data);
    });
}
</script>
</head><body>
<!-- Now use it: -->
<a href="#" onclick='javascript:callpy({"s": "bow", "someother": "argument"});'>CLICK HERE FOR TEST!!!</a>
</body></html>

服务器端(以CGI为例):

#! /usr/bin/env python
import cgi, cgitb
cgitb.enable()
print "Content-Type: text/html'n"
i = cgi.FieldStorage()
if i.has_key("s"):
    if i["s"].value=="bow": print "Yeeeeey!!!! I got 'bow'!!!<br>"
    else: print "Woops! I got", i["s"].value, "instead of 'bow'<br>"
else: print "Argument 's' not present!<br>"
print "All received arguments:"
for x in i.keys(): print x, "<br>"