使用Django运行bash脚本 [英] Run bash script with Django

查看:65
本文介绍了使用Django运行bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是新来的django.按下html中的按钮时,我需要运行bash脚本,并且需要使用Django Framework进行操作,因为我使用它来构建网站.如果有人可以帮助我,我将不胜感激

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

我添加了我的模板和视图,以提供更多帮助.在"nuevaCancion"模板中,我使用2个视图.

I have added my template and my views for being more helpful. In the 'nuevaCancion' template, I use 2 views.

<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

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

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

parser.sh

parser.sh

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

推荐答案

您可以使用空的 form 来完成此操作.

You can do this with empty form.

在模板中制作一个空的 form

In your template make a empty form

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

为您的表单

from django.conf.urls import url

from . import views

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

现在,在您的 views.py 中,您需要从 view 调用 bash.sh 脚本,该脚本会返回您的 template

Now in your views.py you need to call the bash.sh script from the view that returns your 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',{})

我的 test.sh 在主目录中.确保 bash.sh 的第一行具有 sh可执行文件,并且具有正确的权限.您可以授予这样的权限,例如 chmod u + rx bash.sh .

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

#!/bin/sh
echo 'hello'

文件权限 ls〜

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

这篇关于使用Django运行bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆