Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run bash script with Django

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

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

#! /bin/sh
python text4midiALLMilisecs.py tiger.mid
like image 953
Josema_23 Avatar asked Jul 04 '18 16:07

Josema_23


People also ask

How do I run a python program in Django?

The general workflow is as follows: Make changes to the models in your models.py file. Run python manage.py makemigrations to generate scripts in the migrations folder that migrate the database from its current state to the new state. Run python manage.py migrate to apply the scripts to the actual database.

What does Django setup () do?

It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation.


2 Answers

You can do this with empty 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>

Add url for your 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

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.

My test.sh example

#!/bin/sh
echo 'hello'

File permision ls ~

-rwxrw-r--   1 test test    10 Jul  4 19:54  hello.sh*
like image 189
Druta Ruslan Avatar answered Sep 22 '22 20:09

Druta Ruslan


You can refer my blog for detailed explanation >>

http://www.easyaslinux.com/tutorials/devops/how-to-run-execute-any-script-python-perl-ruby-bash-etc-from-django-views/

I would suggest you to use Popen method of Subprocess module. Your shell script can be executed as system command with Subprocess.

Here is a little help.

Your views.py should look like this.

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

Configure your urls.py to call the view function "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

like image 29
Nijil Avatar answered Sep 23 '22 20:09

Nijil