Python django.core.management.execute_from_command_line() Examples

The following are 17 code examples of django.core.management.execute_from_command_line(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.management , or try the search function .
Example #1
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 7 votes vote down vote up
def execute_from_command_line():
    # Limit concurrency in all thread-pools to ONE.
    from maasserver.utils import threads

    threads.install_default_pool(maxthreads=1)
    threads.install_database_unpool(maxthreads=1)
    # Disable all database connections in the reactor.
    from maasserver.utils import orm
    from twisted.internet import reactor

    assert not reactor.running, "The reactor has been started too early."
    reactor.callFromThread(orm.disable_all_database_connections)
    # Configure logging; Django is no longer responsible for this. Behave as
    # if we're always at an interactive terminal (i.e. do not wrap stdout or
    # stderr with log machinery).
    from provisioningserver import logger

    logger.configure(mode=logger.LoggingMode.COMMAND)
    # Hand over to Django.
    from django.core import management

    management.execute_from_command_line() 
Example #2
Source File: runtests.py    From wagtailmenus with MIT License 6 votes vote down vote up
def runtests():
    parsed_args, unparsed_args = parse_args()

    only_wagtailmenus = r'^wagtailmenus(\.|$)'
    if parsed_args.deprecation == 'all':
        # Show all deprecation warnings from all packages
        warnings.simplefilter('default', category=DeprecationWarning)
        warnings.simplefilter('default', category=PendingDeprecationWarning)
    elif parsed_args.deprecation == 'pending':
        # Show all deprecation warnings
        warnings.filterwarnings('default', category=DeprecationWarning, module=only_wagtailmenus)
        warnings.filterwarnings('default', category=PendingDeprecationWarning, module=only_wagtailmenus)
    elif parsed_args.deprecation == 'imminent':
        # Show only imminent deprecation warnings
        warnings.filterwarnings('default', category=DeprecationWarning, module=only_wagtailmenus)
    elif parsed_args.deprecation == 'none':
        # Deprecation warnings are ignored
        pass

    argv = [sys.argv[0], 'test'] + unparsed_args
    return execute_from_command_line(argv) 
Example #3
Source File: manage.py    From django-pyqt with MIT License 5 votes vote down vote up
def execute_django_command(cmd):
    command = ['manage.py']
    command.extend(cmd)
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    return execute_from_command_line(command) 
Example #4
Source File: update_messages.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def django_admin(*args):
    """Executes a django admin tool from the app directory."""
    cwd = os.getcwd()
    os.chdir(os.environ['APP_DIR'])
    management.execute_from_command_line(['django-admin.py'] + list(args))
    os.chdir(cwd) 
Example #5
Source File: region_script.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def run_django(is_snap, is_devenv):
    # Force the production MAAS Django configuration.
    if is_snap:
        snap_data = os.environ["SNAP_DATA"]
        os.environ.update(
            {
                "DJANGO_SETTINGS_MODULE": "maasserver.djangosettings.snappy",
                "MAAS_PATH": os.environ["SNAP"],
                "MAAS_ROOT": snap_data,
                "MAAS_DATA": os.path.join(os.environ["SNAP_COMMON"], "maas"),
                "MAAS_REGION_CONFIG": os.path.join(snap_data, "regiond.conf"),
                "MAAS_DNS_CONFIG_DIR": os.path.join(snap_data, "bind"),
                "MAAS_PROXY_CONFIG_DIR": os.path.join(snap_data, "proxy"),
                "MAAS_SYSLOG_CONFIG_DIR": os.path.join(snap_data, "syslog"),
                "MAAS_IMAGES_KEYRING_FILEPATH": (
                    "/snap/maas/current/usr/share/keyrings/"
                    "ubuntu-cloudimage-keyring.gpg"
                ),
                "MAAS_THIRD_PARTY_DRIVER_SETTINGS": os.path.join(
                    os.environ["SNAP"], "etc/maas/drivers.yaml"
                ),
            }
        )
    elif is_devenv:
        os.environ[
            "DJANGO_SETTINGS_MODULE"
        ] = "maasserver.djangosettings.development"
    else:
        os.environ[
            "DJANGO_SETTINGS_MODULE"
        ] = "maasserver.djangosettings.settings"

    # Let Django do the rest.
    from django.core import management

    management.execute_from_command_line() 
Example #6
Source File: cli.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def run_regiond_command(management, parser):
    """Called to run the regiond command.

    The command itself is sys.argv[1] so that is not passed into this function.
    """
    # At present, only root should execute regiond commands
    if os.getuid() != 0:
        raise SystemExit("You can only '%s' as root." % sys.argv[1])
    management.execute_from_command_line() 
Example #7
Source File: setup.py    From django-actistream with MIT License 5 votes vote down vote up
def run_tests(self):
        from django.core import management
        DSM = 'DJANGO_SETTINGS_MODULE'
        if DSM not in os.environ:
            os.environ[DSM] = 'actistream.tests.settings'
        management.execute_from_command_line() 
Example #8
Source File: test_extraction.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_command_help(self):
        with captured_stdout(), captured_stderr():
            # `call_command` bypasses the parser; by calling
            # `execute_from_command_line` with the help subcommand we
            # ensure that there are no issues with the parser itself.
            execute_from_command_line(['django-admin', 'help', 'makemessages']) 
Example #9
Source File: manage.py    From django-pyqt with MIT License 5 votes vote down vote up
def execute_django_command(cmd):
    command = ['manage.py']
    command.extend(cmd)
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    return execute_from_command_line(command) 
Example #10
Source File: manage.py    From django-pyqt with MIT License 5 votes vote down vote up
def execute_django_command(cmd):
    command = ['manage.py']
    command.extend(cmd)
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    return execute_from_command_line(command) 
Example #11
Source File: test_adapter.py    From django-click with MIT License 5 votes vote down vote up
def test_call_cli():
    execute_from_command_line(["./manage.py", "testcmd"])
    with pytest.raises(RuntimeError):
        execute_from_command_line(["./manage.py", "testcmd", "--raise"]) 
Example #12
Source File: setup.py    From django-trackstats with MIT License 5 votes vote down vote up
def run_tests(self):
        from django.core import management
        DSM = 'DJANGO_SETTINGS_MODULE'
        if DSM not in os.environ:
            os.environ[DSM] = 'trackstats.tests.settings'
        management.execute_from_command_line() 
Example #13
Source File: deeru_admin.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def run():
    settings_path = os.path.join(os.getcwd(), 'deeru')
    settings_py = os.path.join(settings_path, 'settings.py')

    if os.path.exists(settings_py):
        sys.path.insert(0, os.getcwd())
        os.environ['DJANGO_SETTINGS_MODULE'] = 'deeru.settings'
    else:
        settings.configure(INSTALLED_APPS=['deeru_cmd.apps.DeerUCmdConfig'])

    management.execute_from_command_line() 
Example #14
Source File: manage.py    From black-widow with GNU General Public License v3.0 5 votes vote down vote up
def django_cmd(args: list):
    if 'runserver' not in args:
        # cd to "web" directory
        os.chdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'web'))
    elif len(args) <= 1:
        bind_host = _get_bind_socket()
        args.append(bind_host)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", WEB_PACKAGE + ".settings")
    management.execute_from_command_line([EXEC_PATH + ' --django', ] + args) 
Example #15
Source File: test_adapter.py    From django-click with MIT License 5 votes vote down vote up
def test_group_command(capsys):
    execute_from_command_line(["./manage.py", "groupcmd"])
    out, err = capsys.readouterr()
    assert out == "group_command\n"

    execute_from_command_line(["./manage.py", "groupcmd", "subcmd1"])
    out, err = capsys.readouterr()
    assert out == "group_command\nSUB1\n"

    execute_from_command_line(["./manage.py", "groupcmd", "subcmd3"])
    out, err = capsys.readouterr()
    assert out == "group_command\nSUB2\n" 
Example #16
Source File: test_adapter.py    From django-click with MIT License 5 votes vote down vote up
def test_django_help(manage):
    # The -h/--help switches cause the program to exit. Invoking the command
    # through execute_from_command_line would cause the test suite to exit as
    # well... this means that we have to call it in a subprocess.
    helps = [
        manage("helpcmd", "-h"),
        manage("helpcmd", "--help"),
        manage("help", "helpcmd"),
    ]
    assert len(set(helps)) == 1

    help_text = helps[0]
    assert b"HELP_CALLED" not in help_text
    assert help_text.startswith(b"Usage: manage.py helpcmd ") 
Example #17
Source File: test_adapter.py    From django-click with MIT License 4 votes vote down vote up
def test_django_verbosity(capsys, manage):
    # Make sure any command can be called, even if it does not explictly
    # accept the --verbosity option
    with pytest.raises(RuntimeError):
        execute_from_command_line(
            ["./manage.py", "testcmd", "--raise", "--verbosity", "1"]
        )

    # Default
    execute_from_command_line(["./manage.py", "ctxverbositycmd"])
    out, err = capsys.readouterr()
    assert out == "1"

    # Explicit
    execute_from_command_line(["./manage.py", "ctxverbositycmd", "--verbosity", "2"])
    out, err = capsys.readouterr()
    assert out == "2"

    # Invalid
    out = manage("ctxverbositycmd", "--verbosity", "4", ignore_errors=True)
    out = out.replace(b"'", b'"')  # may contain both single and double quotes
    assert out == (
        b"Usage: manage.py ctxverbositycmd [OPTIONS]\n"
        b"\n"
        b'Error: Invalid value for "-v" / "--verbosity": 4 is not in the '
        b"valid range of 0 to 3.\n"
    )

    # Default (option)
    execute_from_command_line(["./manage.py", "argverbositycommand"])
    out, err = capsys.readouterr()
    assert out == "1"

    # Explicit (option)
    execute_from_command_line(
        ["./manage.py", "argverbositycommand", "--verbosity", "2"]
    )
    out, err = capsys.readouterr()
    assert out == "2"