首页 > 解决方案 > 使用 Django 运行 bash 脚本

问题描述

我真的是 django 的新手。当我在 html 中按下一个按钮时,我需要运行一个 bash 脚本,并且我需要使用 Django 框架来执行它,因为我用它来构建我的网络。如果有人可以帮助我,我将不胜感激

编辑:我添加了我的模板和我的观点,以便更有帮助。在“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>

视图.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

标签: pythonhtmldjangobashshell

解决方案


你可以用空来做到这一点form

在你的模板中做一个空的form

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

url为您添加form

from django.conf.urls import url

from . import views

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

现在在你的views.py你需要调用返回你的bash.sh脚本viewtemplate

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*

推荐阅读