Django custom commands, start and stop a python file

794 Views Asked by At

I have a Django project which is used to remotely call a python script with predefined arguments (retrieved as a string from database). The python script is designed to loop indefinitely until killed/terminated (and thus I ruled out Popen.communicate() ).

I need the script to get called when Django calls the command script, but if it is already running, terminate it and run it again.

This is all I have written so far:

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import subprocess
from LEDs.models import Led
mwd="wave"
klr="spring"
crc=5
p=subprocess.Popen(["python3", "Ledshine.py", mwd,klr,crc])

class Command(BaseCommand):
    help = 'Executes python script to light up LED'

    def handle(self, *args, **options):
        ld = Led.objects.all()[0]
        mwd= str(ld.mode)
        klr=str(ld.colour)
        crc=str(ld.circuit)
        if p.poll():
            p.terminate()
        #p=subprocess.Popen(["python3", "Ledshine.py", mwd,klr,crc])
0

There are 0 best solutions below