hue-源码-启动命令entry
entry函数
检查输入,设置settings,解析命令;
最后执行execute_from_command_line(sys.argv)
utility = ManagementUtility(argv)
utility.execute()
ManagementUtility类在代码中能执行django-admin.py的命令
然后执行它的execute方法
  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.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=BaseCommand.option_list)
        self.autocomplete()
        try:
			#结果options为空,args有内容
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass # Ignore any option errors at this point.
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help' # Display help if no arguments were given.
        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
        elif subcommand == 'version':
            sys.stdout.write(parser.get_version() + '\n')
    
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
命令解析
    def parse_args(self, args=None, values=None):
        rargs = self._get_args(args)
		##获取values默认值
        if values is None:
            values = self.get_default_values()
        self.rargs = rargs			#runserver	
        self.largs = largs = []		#[]
        self.values = values		#默认值
		#把rargs填充到largs
        try:		
            stop = self._process_args(largs, rargs, values)
        except (BadOptionError, OptionValueError), err:
            self.error(str(err))
        args = largs + rargs
		## 直接返回
        return self.check_values(values, args)
默认的属性如下
{'pythonpath': None, 'verbosity': u'1', 'traceback': None, 'settings': None}
执行self.fetch_command(subcommand).run_from_argv(self.argv)
   def fetch_command(self, subcommand):
        """
        Tries to fetch the given subcommand, printing a message with the
        appropriate command called from the command line (usually
        "django-admin.py" or "manage.py") if it can't be found.
        """
        # Get commands outside of try block to prevent swallowing exceptions
        commands = get_commands()
        try:
            app_name = commands[subcommand]
        except KeyError:
            sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \
                (subcommand, self.prog_name))
            sys.exit(1)
        if isinstance(app_name, BaseCommand):
            # If the command is already loaded, use it directly.
            klass = app_name
        else:
            klass = load_command_class(app_name, subcommand)
        return klass
command内容
def get_commands():
    global _commands
    if _commands is None:
        _commands = dict([(name, 'django.core') for name in find_commands(__path__[0])])
        from django.conf import settings
        try:
            apps = settings.INSTALLED_APPS
        except ImproperlyConfigured:
            apps = []
        for app_name in apps:
            try:
				#找到app路径
                path = find_management_module(app_name)
				# update方法很关键,把命令的名字和
                _commands.update(dict([(name, app_name)
                                       for name in find_commands(path)]))
            except ImportError:
                pass # No management module - ignore this app
    return _commands
{'compilemessages': 'django.core', 'dumpdata': 'django.core', 'sql': 'django.core', 'sqldropindexes': 'django.core', 'sqlcustom': 'django.core', 'createcachetable': 'django.core', 'flush': 'django.core', 'syncdb': 'django.core', 'check': 'django.core', 'sqlinitialdata': 'django.core', 'runserver': 'django.core', 'dbshell': 'django.core', 'runfcgi': 'django.core', 'test': 'django.core', 'sqlclear': 'django.core', 'shell': 'django.core', 'sqlsequencereset': 'django.core', 'testserver': 'django.core', 'makemessages': 'django.core', 'startproject': 'django.core', 'validate': 'django.core', 'sqlall': 'django.core', 'diffsettings': 'django.core', 'inspectdb': 'django.core', 'startapp': 'django.core', 'sqlindexes': 'django.core', 'loaddata': 'django.core', 'cleanup': 'django.core', 'sqlflush': 'django.core'}
打印一下已经安装的应用
appname:.................django.contrib.auth
appname:.................django_openid_auth
appname:.................django.contrib.contenttypes
appname:.................django.contrib.sessions
appname:.................django.contrib.sites
appname:.................django.contrib.staticfiles
appname:.................django.contrib.admincompilemessages
appname:.................django_extensions
appname:.................south
appname:.................babeldjango
appname:.................desktop
appname:.................axes
appname:.................about
appname:.................beeswax
appname:.................useradmin
appname:.................metadata
appname:.................notebook
经过update命令更丰富,把各个app的命令都添加进来了;
{'show_urls': 'django_extensions', 'generate_secret_key': 'django_extensions', 'openid_cleanup': 'django_openid_auth', 'unreferenced_files': 'django_extensions', 'runcherrypyserver': 'desktop', 'compilemessages': 'django.core', 'axes_reset': 'axes', 'dumpdata': 'django.core', 'startproject': 'django.core', 'show_templatetags': 'django_extensions', 'findstatic': 'django.contrib.staticfiles', 'runjob': 'django_extensions', 'sqlcustom': 'django.core', 'runscript': 'django_extensions', 'runserver': 'django.contrib.staticfiles', 'update_permissions': 'django_extensions', 'create_app': 'django_extensions', 'mail_debug': 'django_extensions', 'clear_cache': 'django_extensions', 'config_upgrade': 'desktop', 'drop_test_database': 'django_extensions', 'sqlclear': 'django.core', 'version': 'desktop', 'syncdata': 'django_extensions', 'datamigration': 'south', 'migrationcheck': 'south', 'changepassword': 'django.contrib.auth', 'runcpserver': 'desktop', 'compile_pyc': 'django_extensions', 'sqldropindexes': 'django.core', 'test_windmill': 'desktop', 'testserver': 'south', 'runjobs': 'django_extensions', 'import_ldap_user': 'useradmin', 'export_emails': 'django_extensions', 'sqlsequencereset': 'django.core', 'makemessages': 'django.core', 'create_jobs': 'django_extensions', 'admin_generator': 'django_extensions', 'runprofileserver': 'django_extensions', 'import_ldap_group': 'useradmin', 'print_settings': 'django_extensions', 'axes_list_attempts': 'axes', 'set_default_site': 'django_extensions', 'diffsettings': 'django.core', 'cleanup': 'django.core', 'sqlcreate': 'django_extensions', 'generate_mdl': 'desktop', 'notes': 'django_extensions', 'inspectdb': 'django.core', 'config_dump': 'desktop', 'create_desktop_app': 'desktop', 'notebook_setup': 'notebook', 'clean_pyc': 'django_extensions', 'validate_templates': 'django_extensions', 'loaddata': 'django.core', 'pipchecker': 'django_extensions', 'find_template': 'django_extensions', 'describe_form': 'django_extensions', 'dumpscript': 'django_extensions', 'sqlflush': 'django.core', 'clearsessions': 'django.contrib.sessions', 'clean_history_docs': 'desktop', 'set_fake_passwords': 'django_extensions', 'migrate': 'south', 'sync_s3': 'django_extensions', 'shell': 'django.core', 'createcachetable': 'django.core', 'flush': 'django.core', 'syncdb': 'south', 'convert_to_south': 'south', 'create_test_fs': 'desktop', 'sqlinitialdata': 'django.core', 'runpylint': 'desktop', 'check': 'django.core', 'dbshell': 'django.core', 'runfcgi': 'django.core', 'reset_db': 'django_extensions', 'test': 'desktop', 'graph_models': 'django_extensions', 'close_sessions': 'beeswax', 'config_help': 'desktop', 'create_command': 'django_extensions', 'dbproxy_server': 'notebook', 'passwd': 'django_extensions', 'is_db_alive': 'desktop', 'runserver_plus': 'django_extensions', 'startmigration': 'south', 'useradmin_sync_with_unix': 'useradmin', 'create_proxy_app': 'desktop', 'shell_plus': 'django_extensions', 'graphmigrations': 'south', 'beeswax_install_examples': 'beeswax', 'sql': 'django.core', 'validate': 'django.core', 'sqlall': 'django.core', 'collectstatic': 'django.contrib.staticfiles', 'schemamigration': 'south', 'print_user_for_session': 'django_extensions', 'kt_renewer': 'desktop', 'startapp': 'django.core', 'sqldiff': 'django_extensions', 'create_template_tags': 'django_extensions', 'sync_documents': 'desktop', 'create_user_directories': 'desktop', 'createsuperuser': 'django.contrib.auth', 'set_fake_emails': 'django_extensions', 'close_queries': 'beeswax', 'sync_ldap_users_and_groups': 'useradmin', 'sqlindexes': 'django.core'}
fetch_commands的最后一个方法load_command_class(app_name, subcommand)直接命令
def load_command_class(app_name, name):
    """
    Given a command name and an application name, returns the Command
    class instance. All errors raised by the import process
    (ImportError, AttributeError) are allowed to propagate.
    """
    print '%s.management.commands.%s' % (app_name, name)
    module = import_module('%s.management.commands.%s' % (app_name, name))
    return module.Command()
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号