2

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])
Brian Pace
  • 135
  • 1
  • 13
  • 1
    the easiest and most straightforward way would be to run it as a detached process, use this answer as a guide: https://stackoverflow.com/questions/89228/calling-an-external-command-in-python#2251026 – Mr. Nun. Aug 03 '17 at 11:37
  • I can make out what you mean, and it sounds like a good addition to this code. How can I make it so that it "restarts" (i.e. checks if it is running, if it is then terminate and open it again)? – Brian Pace Aug 03 '17 at 11:45
  • 1
    use system utilities to see if the process is still running (either by name, or, store in the DB it's PID) and if so, kill it and start a new detached process – Mr. Nun. Aug 03 '17 at 12:09
  • Thanks, that did the trick. – Brian Pace Aug 04 '17 at 10:41

0 Answers0