diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py index d8bded0..880114f 100644 --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -15,6 +15,8 @@ def add_arguments(self, parser): help='When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.') parser.add_argument('-i', '--interface', choices=self.shells, dest='interface', help='Specify an interactive interpreter interface. Available options: "ipython" and "bpython"') + parser.add_argument('-c', '--command', dest='command', + help='Instead of opening an interactive shell, run one command as Django and exit.') def _ipython_pre_011(self): """Start IPython pre-0.11""" @@ -62,6 +64,11 @@ def run_shell(self, shell=None): def handle(self, **options): try: + # Just execute this command and get out. + if options['command']: + exec(options['command']) + return + if options['plain']: # Don't bother loading IPython, because the user wants plain Python. raise ImportError diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt index 8d45439..6a99666 100644 --- a/docs/ref/django-admin.txt +++ b/docs/ref/django-admin.txt @@ -966,6 +966,12 @@ behavior you can use the ``--no-startup`` option. e.g.:: django-admin shell --plain --no-startup +.. versionadded:: 1.10 + +You can also pass a command as a string to execute it as Django, like so:: + + django-admin shell --command="import django; print(django.__version__)" + showmigrations [ []] ------------------------------------------ diff --git a/tests/shell/__init__.py b/tests/shell/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/shell/tests.py b/tests/shell/tests.py new file mode 100644 index 0000000..ae3a4e2 --- /dev/null +++ b/tests/shell/tests.py @@ -0,0 +1,15 @@ +from django import __version__ +from django.core.management import call_command +from django.test import SimpleTestCase +from django.test.utils import patch_logger + + +class ShellCommandTestCase(SimpleTestCase): + + def test_command_option(self): + with patch_logger('test', 'info') as logger: + call_command('shell', + command='import django; from logging import getLogger;' + 'getLogger("test").info(django.__version__)') + self.assertEqual(len(logger), 1) + self.assertEqual(logger[0], __version__)