用Django运行bash脚本

Jos*_*_23 4 html python django bash shell

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

编辑:我已添加了我的模板和我的观点以获得更多帮助.在'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>
Run Code Online (Sandbox Code Playgroud)

Views.py

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

    return render(request,'nuevaCancion.html',{})
Run Code Online (Sandbox Code Playgroud)

parser.sh

#! /bin/sh
python text4midiALLMilisecs.py tiger.mid
Run Code Online (Sandbox Code Playgroud)

Dru*_*lan 8

你可以用空做form.

在你的模板中填空 form

# index.html
<form action="{% url 'run_sh' %}" method="POST">
    {% csrf_token %}
    <button type="submit">Call</button>
</form>
Run Code Online (Sandbox Code Playgroud)

添加url为您的form

from django.conf.urls import url

from . import views

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

现在views.py你需要bash.shview那个回复你的脚本调用脚本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',{})
Run Code Online (Sandbox Code Playgroud)

test.sh在主目录中,确保第一行bash.sh拥有sh executable并拥有正确的权限,你可以给出这样的权限chmod u+rx bash.sh.

我的test.sh例子

#!/bin/sh
echo 'hello'
Run Code Online (Sandbox Code Playgroud)

文件permision ls ~

-rwxrw-r--   1 test test    10 Jul  4 19:54  hello.sh*
Run Code Online (Sandbox Code Playgroud)