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])
4
  • 1
    the easiest and most straightforward way would be to run it as a detached process, use this answer as a guide: stackoverflow.com/questions/89228/… Commented Aug 3, 2017 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)? Commented Aug 3, 2017 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 Commented Aug 3, 2017 at 12:09
  • Thanks, that did the trick. Commented Aug 4, 2017 at 10:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.