VisionV VisionV - 1 month ago 4x
Python Question

python django run bash script in server

I would like to create a website-app to run a bash script located in a server. Basically I want this website for:

  • Upload a file

  • select some parameters

  • Run a bash script taking the input file and the parameters

  • Download the results

I know you can do this with php, javascript... but I have never program in these languages. However I can program in python. I have used pyQT library in python for similar purposes.

Can this be done with django? or should I start learning php & javascript?
I cannot find any tutorial for this specific task in Django.


This can be done in Python using the Django framework.

First create a form including a FileField and the fields for the other parameters:

from django import forms

class UploadFileForm(forms.Form):
    my_parameter = forms.CharField(max_length=50)
    file = forms.FileField()

Include the UploadFileForm in your view and call your function for handling the uploaded file:

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            my_parameter = form.cleaned_data['my_parameter']
            # Handle the uploaded file
            results = handle_uploaded_file(request.FILES['file'], title)
            # Clear the form and parse the results
            form = UploadFileForm()
            return render(request, 'upload.html', {'form': form, 'results': results})
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

Create the function to handle the uploaded file and call your bash script:

import subprocess
import os

def handle_uploaded_file(f, my_parameter):
    file_path = os.path.join('/path/to/destination/',
    # Save the file 
    with open(file_path, 'wb+') as destination:
        for chunk in f.chunks():
    # Call your bash script with the
    output = subprocess.check_output(['./',str(file_path),str(my_parameter)], shell=True)
    return output

Check out for more examples and instructions on how the handle file uploads in Django.