Login

Command Line Script Launcher

Author:
dakrauth
Posted:
July 12, 2008
Language:
Python
Version:
.96
Tags:
script management execfile
Score:
2 (after 6 ratings)

I often write short test or development scripts that are intended as one-offs. I typically want to execute these scripts from the command line but am always forgetting the necessary steps to set up the Django environment as described here.

This snippet allows you execute arbitrary Python scripts from the command line with the context of a given project:

python manage.py execfile /path/to/some/script.py

Add the code to a file named execfile.py within the management/commands directory of one of your apps (see here for details).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import sys
from django.utils import termcolors
from django.core.management.base import LabelCommand

style = termcolors.make_style(fg='green', opts=('bold',))

class Command(LabelCommand):
    help = 'Executes the given Python source file under the context of the current Django settings'
    label = 'filename'
    args = '<filename filename ...>'
    requires_model_validation = False

    def handle_label(self, label, **options):
        sys.stderr.write(style('Executing %s' % label) + '\n')
        execfile(label, dict(__name__='__main__'))

More like this

  1. extras.py for management commands by dnordberg 8 years ago
  2. Update All Apps to Latest Revision by dedaluz 7 years, 1 month ago
  3. syncdata command by graham 7 years, 1 month ago
  4. Custom management command to list recent admin actions by pbx 6 years, 1 month ago
  5. Script factory for monitoring django-sphinx with Nagios by johnnoone 6 years, 4 months ago

Comments

Please login first before commenting.