gpt4 book ai didi

python - 使用 Django 运行 bash 脚本

转载 作者:太空狗 更新时间:2023-10-30 01:56:34 26 4
gpt4 key购买 nike

我真的是 django 的新手。当我在 html 中按下按钮时,我需要运行一个 bash 脚本,我需要使用 Django Framework 来完成它,因为我用它来构建我的网站。如果有人能帮助我,我将不胜感激

编辑:为了更有帮助,我添加了我的模板和观点。在“nuevaCancion”模板中,我使用了 2 个 View 。

<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>

View .py

def index(request):
if request.POST:
subprocess.call('/home/josema/parser.sh')

return render(request,'nuevaCancion.html',{})

解析器.sh

#! /bin/sh
python text4midiALLMilisecs.py tiger.mid

最佳答案

您可以使用空的 form 来做到这一点。

在您的模板中制作一个空的表单

# index.html
<form action="{% url 'run_sh' %}" method="POST">
{% csrf_token %}
<button type="submit">Call</button>
</form>

为您的表单添加url

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^run-sh/$', views.index, name='run_sh')
]

现在在您的 views.py 中,您需要从返回您的模板<的view 调用bash.sh 脚本

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',{})

我的 test.sh 在主目录中。确保bash.sh的第一行有sh executable并且有正确的权限。您可以像这样授予权限 chmod u+rx bash.sh

我的test.sh 例子

#!/bin/sh
echo 'hello'

文件权限 ls ~

-rwxrw-r--   1 test test    10 Jul  4 19:54  hello.sh*

关于python - 使用 Django 运行 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com