LoginSignup
1
1

More than 5 years have passed since last update.

Djangoの管理コマンでスクリプトを実行させる

Last updated at Posted at 2012-08-24

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1