我想从我的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
这里的弓是从输入框中获取的。
答案 0 :(得分:2)
直接从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/#call-command
答案 1 :(得分:1)
使用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>"