Skip to content

Instantly share code, notes, and snippets.

@dabrowne
Created March 2, 2018 00:37
Show Gist options
  • Save dabrowne/46bf84a88e211e9a7262ee4bb57163c5 to your computer and use it in GitHub Desktop.
Save dabrowne/46bf84a88e211e9a7262ee4bb57163c5 to your computer and use it in GitHub Desktop.
Django autoreload management command
from django.core.management import BaseCommand
from django.utils import autoreload
import atexit
import subprocess
import sys
class Command(BaseCommand):
"""
Basic management command which will execute a process using the same
autoreload mechanism used by the runserver command. Processes run with
this command will be reloaded when changes are made to source files.
A simple alternative to the Watchdog/watchmedo utility. Will also
detects changes made to shared files/directories in a VM - Watchdog
doesn't do this well.
TODO: Allow specification of signal used to restart the process
(i.e. SIGTERM/SIGKILL)
Examples:
./manage.py autoreload -- celery -A <project_name> worker -l info
"""
help = "Run and auto-reload a process using the default django autoreloader"
def handle(self, *args, **options):
self.command = options['command']
autoreload.main(self.run_process)
def add_arguments(self, parser):
parser.add_argument('command', nargs='+')
def run_process(self):
process = subprocess.Popen(self.command)
atexit.register(process.terminate)
sys.exit(process.wait())
@Kub-AT
Copy link

Kub-AT commented Oct 16, 2020

Thanks!

From django 2.x you should use autoreload.run_with_reloader instead of autoreload.main

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment