使用 Django 运行 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51178003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run bash script with Django
提问by Josema_23
I'm really new in django. I need to run a bash script when I push a button in html, and I need to do it with Django Framework, because I used it to build my web. I'd be grateful if anybody could help me
我真的是 Django 的新手。当我在 html 中按下一个按钮时,我需要运行一个 bash 脚本,我需要用 Django 框架来完成,因为我用它来构建我的 web。如果有人能帮助我,我将不胜感激
Edit: I have added my template and my views for being more helpful. In the 'nuevaCancion' template, I use 2 views.
编辑:为了更有帮助,我添加了我的模板和我的观点。在“nuevaCancion”模板中,我使用了 2 个视图。
<body>
{% block cabecera %}
<br><br><br>
<center>
<h2> <kbd>Nueva Cancion</kbd> </h2>
</center>
{% endblock %}
{% block contenido %}
<br><br>
<div class="container">
<form id='formulario' method='post' {% if formulario.is_multipart %} enctype="multipart/form-data" {% endif %} action=''>
{% csrf_token %}
<center>
<table>{{formulario}}</table>
<br><br>
<p><input type='submit' class="btn btn-success btn-lg" value='A?adir'/>
<a href="/ListadoCanciones/" type="input" class="btn btn-danger btn-lg">Cancelar</a></p>
</center>
</form>
<br>
</div>
<center>
<form action="" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-warning btn-lg">Call</button>
</form>
</center>
{% endblock %}
</body>
Views.py
视图.py
def index(request):
if request.POST:
subprocess.call('/home/josema/parser.sh')
return render(request,'nuevaCancion.html',{})
parser.sh
解析器
#! /bin/sh
python text4midiALLMilisecs.py tiger.mid
回答by Druta Ruslan
You can do this with empty form
.
你可以用空来做到这一点form
。
In your template make a empty form
在你的模板中做一个空 form
# index.html
<form action="{% url 'run_sh' %}" method="POST">
{% csrf_token %}
<button type="submit">Call</button>
</form>
Add url
for your form
url
为您添加form
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^run-sh/$', views.index, name='run_sh')
]
Now in your views.py
you need to call the bash.sh
script from the view
that returns your template
现在,您views.py
需要bash.sh
从view
返回您的脚本中调用脚本template
import subprocess
def index(request):
if request.POST:
# give the absolute path to your `text4midiAllMilisecs.py`
# and for `tiger.mid`
# subprocess.call(['python', '/path/to/text4midiALLMilisecs.py', '/path/to/tiger.mid'])
subprocess.call('/home/user/test.sh')
return render(request,'index.html',{})
My test.sh
is in the home directory. Be sure that the first line of bash.sh
have sh executable
and also have right permission. You can give the permissions like this chmod u+rx bash.sh
.
我test.sh
的在主目录中。确保第一行的bash.sh
havesh executable
和 also has right 权限。您可以授予这样的权限chmod u+rx bash.sh
。
My test.sh
example
我的test.sh
例子
#!/bin/sh
echo 'hello'
File permision ls ~
文件权限 ls ~
-rwxrw-r-- 1 test test 10 Jul 4 19:54 hello.sh*
回答by Nijil
You can refer my blog for detailed explanation >>
详细解释可以参考我的博客>>
I would suggest you to use Popen method of Subprocess module. Your shell script can be executed as system command with Subprocess.
我建议您使用 Subprocess 模块的 Popen 方法。您的 shell 脚本可以作为系统命令与 Subprocess 一起执行。
Here is a little help.
这里有一点帮助。
Your views.pyshould look like this.
您的views.py应如下所示。
from subprocess import Popen, PIPE, STDOUT
from django.http import HttpResponse
def main_function(request):
if request.method == 'POST':
command = ["bash","your_script_path.sh"]
try:
process = Popen(command, stdout=PIPE, stderr=STDOUT)
output = process.stdout.read()
exitstatus = process.poll()
if (exitstatus==0):
result = {"status": "Success", "output":str(output)}
else:
result = {"status": "Failed", "output":str(output)}
except Exception as e:
result = {"status": "failed", "output":str(e)}
html = "<html><body>Script status: %s \n Output: %s</body></html>" %(result['status'],result['output'])
return HttpResponse(html)
In this example, stderr and stdout of the script is saved in variable 'output', And exit code of the script is saved in variable 'exitstatus'.
在这个例子中,脚本的stderr和stdout保存在变量' output'中,脚本的退出代码保存在变量' exitstatus'中。
Configure your urls.pyto call the view function "main_function".
配置您的urls.py以调用视图函数“ main_function”。
url(r'^the_url_to_run_the_script$', main_function)
Now you can run the script by calling http://server_url/the_url_to_run_the_script
现在您可以通过调用http://server_url/the_url_to_run_the_script来运行脚本
回答by Muhtar
You can use python module subprocessin your view.
您可以在视图中使用 python 模块子进程。
import subprocess
def your_view(request):
subprocess.call('your_script.sh')
回答by Shiri
Do it with Python:
用 Python 来做:
With Subprocess:
使用子流程:
import subprocess
proc = subprocess.Popen("ls -l", stdout=subprocess.PIPE)
output, err = proc.communicate()
print output
Or with os
module:
或使用os
模块:
import os
os.system('ls -l')