management.py application commands and one off scripts

281 views
Skip to first unread message

Graham Carlyle

unread,
Aug 22, 2007, 11:05:57 AM8/22/07
to django...@googlegroups.com
The pending ability to allow custom application commands made me think
about a few on-off scripts i have that i wouldn't want to have available
as a command but do django stuff from the command line.

Maybe its worth adding a new core command for invoke these sorts of
scripts? Rather than having to manipulate the sys.path & os.environ in
each case.

--
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
help = "Runs a python script in the django environment."
args = '[script] [args...]'

def handle(self, *args, **options):
script = args[0]
execfile(script)
--
from fooapp import models

print models.Bar.objects.get(name=args[1])
--
./manage runscript hacks/printbar.py "bob"
--

hmm... or maybe not

Graham

George Vilches

unread,
Aug 22, 2007, 11:13:51 AM8/22/07
to django...@googlegroups.com
Graham Carlyle wrote:
> The pending ability to allow custom application commands made me think
> about a few on-off scripts i have that i wouldn't want to have available
> as a command but do django stuff from the command line.
>
> Maybe its worth adding a new core command for invoke these sorts of
> scripts? Rather than having to manipulate the sys.path & os.environ in
> each case.

I want that command to. In the meantime though, we've got a command
that runs like this:

python test_shell.py <module.path.name>

Drop that test_shell.py in the root of your app. It's this:

test_shell.py
------
#!/usr/bin/env python
from django.core.management import execute_manager, setup_environ
import sys
try:
import settings # Assumed to be in the same directory.
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the
directory containing %r. It appears you've customized things.\nYou'll
have to run django-admin.py, passing it your settings module.\n(If the
file settings.py does indeed exist, it's causing an ImportError
somehow.)\n" % __file__)
sys.exit(1)

project_directory = setup_environ(settings)

from django.db.models.loading import get_models
loaded_models = get_models()

if sys.argv and len(sys.argv) > 1:
__import__(sys.argv[1])
else:
print 'test_shell.py <module>'


That work for you in the meantime? Should give your script equivalent
capabilities to "shell".

George

Graham Carlyle

unread,
Aug 23, 2007, 4:39:26 AM8/23/07
to django...@googlegroups.com
or maybe manage.py/django-admin.py could take an new option for an
additional directory to search for commands (as well as the core dir,
and application dir when it gets checked in again). Then the one off
scripts could be written in the style of commands.

Graham

Reply all
Reply to author
Forward
0 new messages