当前位置: 首页>>代码示例>>Python>>正文


Python CommandParser.parse_known_args方法代码示例

本文整理汇总了Python中django.core.management.base.CommandParser.parse_known_args方法的典型用法代码示例。如果您正苦于以下问题:Python CommandParser.parse_known_args方法的具体用法?Python CommandParser.parse_known_args怎么用?Python CommandParser.parse_known_args使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.management.base.CommandParser的用法示例。


在下文中一共展示了CommandParser.parse_known_args方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: execute

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
开发者ID:AaronLaw,项目名称:django,代码行数:60,代码来源:__init__.py

示例2: run_default_tests

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
def run_default_tests(command_line_args):
    # This reproduces the logic used by execute_from_command_line to
    # extra whether the subcommand is "test" and whether a settings
    # module has been manually specified.
    try:
        subcommand = command_line_args[1]
    except IndexError:
        return False

    parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
    parser.add_argument('--settings')
    parser.add_argument('--pythonpath')
    parser.add_argument('args', nargs='*')
    try:
        options, args = parser.parse_known_args(command_line_args[2:])
    except CommandError:
        # Ignore any errors, we just wanted to extract any settings option
        # that might have been specified.
        options = {'settings': None}

    return subcommand == 'test' and not options.settings
开发者ID:Geo-InformationSocietyofKenya,项目名称:pombola,代码行数:23,代码来源:manage.py

示例3: execute

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser('django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
开发者ID:JBKahn,项目名称:django,代码行数:75,代码来源:__init__.py

示例4: execute

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
    def execute(self, argv=None, stdout=None, stderr=None):

        if argv is None:
            argv = sys.argv

        if stdout is None:
            stdout = sys.stdout

        if stderr is None:
            stderr = sys.stderr

        if django.VERSION >= (1, 8):
            from django.core.management.base import CommandParser
            parser = CommandParser(None,
                usage="%(prog)s subcommand [options] [args]",
                add_help=False)
            parser.add_argument('--version', action='store_true', help="show program's version number and exit")
            parser.add_argument('-h', '--help', action='store_true', help="show this help message and exit")

            try:
                options, argv = parser.parse_known_args(argv)
            except:
                pass  # Ignore any option errors at this point.
        else:
            from django.core.management import LaxOptionParser

            parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                option_list=(),
                add_help_option=False)
            parser.add_option('--version', action='store_true', help="show program's version number and exit")
            parser.add_option('-h', '--help', action='store_true', help="show this help message and exit")

            try:
                options, argv = parser.parse_args(argv)
            except:
                pass  # Ignore any option errors at this point.

        if len(argv) > 1:
            subcommand = argv[1]
        else:
            subcommand = 'help'  # Display help if no arguments were given.


        if options.help:

            if subcommand == 'help':
                if hasattr(parser, 'print_lax_help'):
                    parser.print_lax_help()
                else:
                    parser.print_help(stdout)
                stdout.write(self.main_help_text() + '\n')
            else:
                command = self.fetch_command(subcommand)
                if command is not None:
                    command.print_help(self.prog_name, subcommand, file=stdout)
                else:
                    stdout.write(self.unknown_command_text(subcommand) + '\n')

        elif subcommand == 'version' or options.version:

            stdout.write(wirecloud.platform.__version__ + '\n')

        elif subcommand == 'help':

            if len(argv) <= 2:
                if hasattr(parser, 'print_lax_help'):
                    parser.print_lax_help()
                else:
                    parser.print_help(stdout)
                stdout.write(self.main_help_text() + '\n')
            elif argv[2] == '--commands':
                stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                command = self.fetch_command(argv[2])
                if command is not None:
                    command.print_help(self.prog_name, argv[2], file=stdout)
                else:
                    stdout.write(self.unknown_command_text(argv[2]) + '\n')

        else:
            command = self.fetch_command(subcommand)
            if command is not None:
                command.run_from_argv(argv, stdout=stdout, stderr=stderr)
            else:
                stdout.write(self.unknown_command_text(subcommand) + '\n')
开发者ID:rachmadagitam,项目名称:apps.Wirecloud,代码行数:87,代码来源:wirecloud_admin.py

示例5: execute

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
    def execute(self):
        """
        Given the command-line arguments, figure out which subcommand is being
        run, create a parser appropriate to that command, and run it.
        """
        # 先找出二级指令,没有二级指令就打印帮助信息
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # 预处理的选项,这些选项会和当前传递的选项有冲突,所以先解析出这些选项,这样用户传递的选项才不会被影响.
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        # 这里是指定settings文件
        parser.add_argument('--settings')
        # 这里是指定python路径
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            # 修改环境settings和pythonpath
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            # django在启动时会创建settings = LazySettings()
            # 通过读取os.environ.get('DJANGO_SETTINGS_MODULE'),来初始化settings对象
            # settings是一个lazy对象,使用self._wrapped保存Settings对象,当读取属性时,lazy对象会先进行_setup,然后会调用getattr(self._wrapped,key)
            # 当要读取INSTALLED_APPS时,会先进行_setup
            # 说白了就是LazySetting对象读取属性时,会真正初始化Settings对象,并赋值给LazySetting._wrapped=Settings()
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc

        if settings.configured:
            # 就是返回self._wrapped is not empty,当前是否已经初始化好了settings
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    # 执行django.setup,如果有错误那么
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser('django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                # 执行django.setup
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            # 这里执行fetch_command('runserver').run_from_argv(['/Users/mering/Proje...manage.py', 'runserver', '--noreload', '--nothreading'])
            # runserver 对应的是django.contrib.staticfiles
            # 加载该class import_module('%s.management.commands.%s' % (app_name, name))
            # import_module('django.contrib.staticfiles.management.commands.runserver')
            # 放回的fetch_command(subcommand)=django.contrib.staticfiles.management.commands.runserver.Command()
            # django.contrib.staticfiles.management.commands.runserver.Command继承自django.core.management.Command,
            # run_from_argv会调用django.core.management.Command.excute-->django.core.management.BaseCommand.excute
            # django.core.management.commands.runserver.Command.handle
            # django.core.management.commands.runserver.Command.run
            # django.core.management.commands.runserver.Command.inner_run
            # django.contrib.staticfiles.management.commands.runserver.Command.get_handler  获得wsgiapp
            #  Debug模式下返回StaticFilesHandler
            # django.core.servers.run
            # def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
            #     server_address = (addr, port)
#.........这里部分代码省略.........
开发者ID:canhuayin,项目名称:note,代码行数:103,代码来源:__init__.py

示例6:

# 需要导入模块: from django.core.management.base import CommandParser [as 别名]
# 或者: from django.core.management.base.CommandParser import parse_known_args [as 别名]
from __future__ import unicode_literals
开发者ID:letouriste001,项目名称:SmartForest_2.0,代码行数:3,代码来源:__init__.py


注:本文中的django.core.management.base.CommandParser.parse_known_args方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。