- July 12, 2008
- script management execfile
- 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__'))