Run scripts with Django's admin command

A custom command class that lets you run Python scripts in your Django environment from Django admin commands.

If it catches any exception, it throws a stack trace to the logger and returns status code 1.

I use it like this.

$ python manage.py script do_something.py && do_next || else_do

app/management/commands/script.py


# -*- coding: utf-8


import sys
import logging

from django.core.management.base import LabelCommand, CommandError


logger = logging.getLogger(__name__)


class Command(LabelCommand):
    help = u'Executes the specified script file in current context.'
    args = u'[file]'
    label = u'script file'

    # Prevent to validate installed models.
    requires_model_validation = False

    def handle_label(self, label, **options):
        try:
            locals_ = {u'__name__': u'__main__'}
            globals_ = {}
            execfile(label, locals_, globals_)
        except Exception:
            logger.exception(u'Got an error in executing %s.' % label)
            raise CommandError

Recommended Posts

Run scripts with Django's admin command
How to use ManyToManyField with Django's Admin
Compile and run Rust with a single command
Run Python with VBA
Run prepDE.py with python3
Run Blender with python
Control scripts with exceptions
Run iperf with python
Run python with PyCharm (Windows)
Touch Flask + run with Heroku
Run Python with CloudFlash (arm926ej-s)
Let's run Excel with Python
Alternative to django's dumpdata command
To run gym_torcs with ubutnu16
One-liner addition with various scripts
Run unix command on python
Run Label with tkinter [Python]
Run Apache-Spark with IPython Notebook
I compared Django's admin screens
Run DHT22 with RasPi + Python
Encryption / decryption with GPG command