Login

Command Line Script Launcher

Author:
dakrauth
Posted:
July 12, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.