Djangoの管理コマンドから, Djangoの環境でPythonスクリプトを実行させるカスタムコマンドクラス.
何らかの例外をキャッチすると, ロガーにスタックトレースを吐いて, ステータスコード1を返す.
こんなかんじに使う.
$ 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