Parses commandline options, updates config, creates and runs the application.

    Supports listing and selecting environment configurations if `Flask-Config`_ configuration class is used.

    .. _Flask-Config: http://pypi.python.org/pypi/Flask-Config
430298
def run(create_app, config, description=None, args=None, namespace=None, options=None):
    
    import argparse

    class HelpFormatter(
        # argparse.RawTextHelpFormatter,
        argparse.RawDescriptionHelpFormatter,
        # argparse.ArgumentDefaultsHelpFormatter,
        # argparse.HelpFormatter,
        ):
        pass

    # Get configurations data if
    envName = getattr(config, 'ENV', None)
    envMap = getattr(config, 'envMap', None)
    envHelp = getattr(config, 'envHelp', {})
    envSelectVar = getattr(config, 'envSelectVar', None)
    configurations = getattr(config, 'configurations', None)
    envSelectable = callable(getattr(config, 'select', None))
    envPrintable = config.__str__ is not object.__str__

    parser = argparse.ArgumentParser(
        description = description or getattr(config, 'description',
            'runs Flask-based web application using Python WSGI reference server'),
        epilog = ''.join((
            '\n\noptional environment variables:\n{}'.format(
                '\n'.join(sorted('  {:<20}  {}'.format(envMap[key], envHelp.get(key, ''))
                for key in envMap))) if envMap else '',
            '\n\navailable environment configurations (*: active):\n{}'.format(
                '\n'.join('{} {}'.format(
                    '*' if envName in c.names else ' ',
                    ' | '.join(c.names)
                ) for c in configurations)) if configurations else '',
        )),
        formatter_class = HelpFormatter)

    parser.add_argument('-b', '--bind', metavar='[HOST|:PORT]', default='127.0.0.1:5000',
        help = 'bind to HOST:PORT (default: 127.0.0.1:5000)')

    debug = config.DEBUG
    debugMsg = ' (default in {})'.format(config.ENV)
    debugTrueMsg = debugMsg if debug else ''
    debugFalseMsg = debugMsg if not debug else ''

    parser.add_argument('-r', '--reload', action='store_true', default=debug,
        help = 'reload server on code change' + debugTrueMsg)
    parser.add_argument('-R', '--no-reload', action='store_false', dest='reload',
        help = 'do not reload server on code change' + debugFalseMsg)

    parser.add_argument('-d', '--debug', action='store_true', default=debug,
        help = 'show debugger on exception' + debugTrueMsg)
    parser.add_argument('-D', '--no-debug', action='store_false', dest='debug',
        help = 'do not show debugger on exception' + debugFalseMsg)

    if envSelectable:
        parser.add_argument('-e', '--env', default=config.ENV,
            help = 'select environment config (default: {})'.format(config.ENV))

    if envPrintable:
        if envSelectable:
            parser.add_argument('-E', '--show-env', nargs='?', const=True,
                help = 'show environment config and exit ({}default: {})'
                    .format('*: all, ' if configurations else '', config.ENV))
        else:
            parser.add_argument('-E', '--show-env', action='store_true',
                help = 'show environment config and exit')

    parser.add_argument('-g', '--gen-key', action='store_true',
        help = 'generate a good secret key and exit')


    args = parser.parse_args(args, namespace)

    if args.gen_key:
        # See http://flask.pocoo.org/docs/0.10/quickstart/#sessions
        import os
        key = os.urandom(24)
        return print(key)
        # return print('{0}\n{0!r}'.format(key))

    if envSelectable and args.env:
        config = config.select(args.env)

    if envPrintable and args.show_env:
        if configurations and args.show_env == '*':
            print('\n\n'.join('# {}\n{}'.format(' | '.join(c.names), c) for c in configurations))
        elif args.show_env is True:
            print(config)
        else:
            print(config.select(args.show_env))

        return

    host, port = (args.bind + ':').split(':')[:2]
    host = host or '127.0.0.1'
    port = int(port) if port else 5000

    return create_app(config).run(host, port, args.debug, use_reloader=args.reload, **(options or {}))
1182772
def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
    

    # Set up the command-line options
    parser = optparse.OptionParser()
    parser.add_option(
        "-H",
        "--host",
        help="Hostname of the Flask app " + "[default %s]" % default_host,
        default=default_host,
    )
    parser.add_option(
        "-P",
        "--port",
        help="Port for the Flask app " + "[default %s]" % default_port,
        default=default_port,
    )

    # Two options useful for debugging purposes, but
    # a bit dangerous so not exposed in the help message.
    parser.add_option(
        "-d", "--debug", action="store_true", dest="debug", help=optparse.SUPPRESS_HELP
    )
    parser.add_option(
        "-p",
        "--profile",
        action="store_true",
        dest="profile",
        help=optparse.SUPPRESS_HELP,
    )

    options, _ = parser.parse_args()

    # If the user selects the profiling option, then we need
    # to do a little extra setup
    if options.profile:
        from werkzeug.contrib.profiler import ProfilerMiddleware

        app.config["PROFILE"] = True
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
        options.debug = True

    app.run(debug=options.debug, host=options.host, port=int(options.port))
597120
def create_app():
    
    app = App.create_app(__name__)
    app.configure('.configs.settings')

    # yes, I should use blueprints; but I don't really care for such a small
    # toy app
    @app.route('/config')
    def get_config():
        """Get the current configuration of the app."""
        return jsonify(app.config)

    @app.route('/put_config', methods=['PUT'])
    def put_config():
        """Add to the current configuration of the app.

        Takes any JSON body and adds all keys to the configs with the provided
        values.
        """
        data = request.json()

        for key, val in data.items():
            app.config[key] = val

        return jsonify({'message': 'Config updated!'})

    return app
274042
def run(self):
        
        self.call_plugins("on_run")
        if vars(self.arguments).get("version", None):
            self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version))
        else:
            if self.arguments.command == "main":
                self.main()
            else:
                self.subcommands[self.arguments.command].run()
        self.call_plugins("on_end")
425861
def do_config(self, arg):
        
        if arg['print']:
            self.print_config(arg)
        elif arg['reload']:
            self.reload_config(arg)
        else:
            self.help_server()
610052
def run_configure(self, mandatory=True):
        
        if not has_file(self.working_dir, 'configure'):
            if mandatory:
                raise FileNotFoundError(
                    "Could not find a configure script for execution.")
            else:
                return
        try:
            prog = RunningProgram(self, 'configure')
            prog.expect_exit_status(0)
        except Exception:
            if mandatory:
                raise
759589
def run(self):
        
        opt_parser = setup_opt_parser()
        (self.options, remaining_args) = opt_parser.parse_args()
        logger = self.set_log_level()

        pkg_spec = validate_pypi_opts(opt_parser)
        if not pkg_spec:
            pkg_spec = remaining_args
        self.pkg_spec = pkg_spec

        if not self.options.pypi_search and (len(sys.argv) == 1 or\
                len(remaining_args) > 2):
            opt_parser.print_help()
            return 2

        #Options that depend on querying installed packages, not PyPI.
        #We find the proper case for package names if they are installed,
        #otherwise PyPI returns the correct case.
        if self.options.show_deps or self.options.show_all or \
                self.options.show_active or self.options.show_non_active  or \
                (self.options.show_updates and pkg_spec):
            want_installed = True
        else:
            want_installed = False
        #show_updates may or may not have a pkg_spec
        if not want_installed or self.options.show_updates:
            self.pypi = CheeseShop(self.options.debug)
            #XXX: We should return 2 here if we couldn't create xmlrpc server

        if pkg_spec:
            (self.project_name, self.version, self.all_versions) = \
                    self.parse_pkg_ver(want_installed)
            if want_installed and not self.project_name:
                logger.error("%s is not installed." % pkg_spec[0])
                return 1

        #I could prefix all these with 'cmd_' and the methods also
        #and then iterate over the `options` dictionary keys...
        commands = ['show_deps', 'query_metadata_pypi', 'fetch',
                'versions_available', 'show_updates', 'browse_website',
                'show_download_links', 'pypi_search', 'show_pypi_changelog',
                'show_pypi_releases', 'yolk_version', 'show_all',
                'show_active', 'show_non_active', 'show_entry_map',
                'show_entry_points']

        #Run first command it finds, and only the first command, then return
        #XXX: Check if more than one command was set in options and give error?
        for action in commands:
            if getattr(self.options, action):
                return getattr(self, action)()
        opt_parser.print_help()
987627
def run_command(self, config_file, sources):
        
        config = configparser.ConfigParser()
        config.read(config_file)

        rdbms = config.get('database', 'rdbms').lower()

        loader = self.create_routine_loader(rdbms)
        status = loader.main(config_file, sources)

        return status
271124
def run(self, exp_config=None, app_id=None, bot=False, **kwargs):
        
        import dallinger as dlgr

        app_id = self.make_uuid(app_id)

        if bot:
            kwargs["recruiter"] = "bots"

        self.app_id = app_id
        self.exp_config = exp_config or kwargs
        self.update_status("Starting")
        try:
            if self.exp_config.get("mode") == "debug":
                dlgr.command_line.debug.callback(
                    verbose=True, bot=bot, proxy=None, exp_config=self.exp_config
                )
            else:
                dlgr.deployment.deploy_sandbox_shared_setup(
                    dlgr.command_line.log,
                    app=app_id,
                    verbose=self.verbose,
                    exp_config=self.exp_config,
                )
        except Exception:
            self.update_status("Errored")
            raise
        else:
            self.update_status("Running")
        self._await_completion()
        self.update_status("Retrieving data")
        data = self.retrieve_data()
        self.update_status("Completed")
        return data
992477
def execute(self, callback=None):
        
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        self.parser = parser = NewOptionParser(prog=self.prog_name,
                             usage=self.usage_info,
#                             version=self.get_version(),
                             formatter = NewFormatter(),
                             add_help_option = False,
                             option_list=self.option_list)
        
        if not self.global_options:
            global_options, args = parser.parse_args(self.argv)
            global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps'))
            handle_default_options(global_options)
            args = args[1:]
        else:
            global_options = self.global_options
            args = self.argv

        if global_options.envs:
            for x in global_options.envs:
                if '=' in x:
                    k, v = x.split('=')
                    os.environ[k.strip()] = v.strip()
                else:
                    print ('Error: environment variable definition (%s) format is not right, '
                           'shoule be -Ek=v or -Ek="a b"' % x)

        global_options.settings = global_options.settings or os.environ.get('SETTINGS', 'settings.ini')
        global_options.local_settings = global_options.local_settings or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini')
        
        if callback:
            callback(global_options)
            
        if len(args) == 0:
            if global_options.version:
                print self.get_version()
                sys.exit(0)
            else:
                self.print_help(global_options)
                sys.ext(1)

        self.do_command(args, global_options)
608681
def run(self):
        
        config_h = opj("src", "cysignals", "cysignals_config.h")
        if not os.path.isfile(config_h):
            import subprocess
            subprocess.check_call(["make", "configure"])
            subprocess.check_call(["sh", "configure"])

        dist = self.distribution
        ext_modules = dist.ext_modules
        if ext_modules:
            dist.ext_modules[:] = self.cythonize(ext_modules)

        _build.run(self)
1103340
def initialize(self, app: Flask, app_config):
        
        debug = app_config["debug"]
        port = app_config["http.port"]
        if debug:
            self.started_on_port = port
            app.run(host="0.0.0.0", debug=True, port=port)
        else:
            for port in range(port, port + 50):
                self.http_server = WSGIServer(('0.0.0.0', port), app)
                try:
                    self.http_server.start()
                except OSError:
                    # try next port
                    continue
                self.started_on_port = port
                break
1270416
def run(quiet, args):
    
    if not args:
        raise ClickException('pass a command to run')

    cmd = ' '.join(args)
    application = get_current_application()
    name = application.name
    settings = os.environ.get('DJANGO_SETTINGS_MODULE', '%s.settings' % name)
    return application.run(
        cmd,
        verbose=not quiet,
        abort=False,
        capture=True,
        env={
            'DJANGO_SETTINGS_MODULE': settings
        }
    )
1266513
def __parse_config(self):
        

        if self.should_parse_config and (self.args.config or self.config_file):
            self.config = ConfigParser.SafeConfigParser()
            self.config.read(self.args.config or self.config_file)
811453
def execute(self):
        
        #Initialize the option parser
        parser = LaxOptionParser(
            usage="%prog subcommand [options] [args]",
            option_list=BaseCommand.option_list #This will define what is allowed input to the parser (ie --settings=)
        )

        #Parse the options
        options, args = parser.parse_args(self.argv)
        #Handle --settings and --pythonpath properly
        options = handle_default_options(options)

        try:
            #Get the name of the subcommand
            subcommand = self.argv[1]
        except IndexError:
            #If the subcommand name cannot be found, set it to help
            subcommand = 'help'

        #If the subcommand is help, print the usage of the parser, and available command names
        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_help()
                sys.stdout.write(self.help_text + '\n')
        else:
            #Otherwise, run the given command
            self.fetch_command(subcommand).run_from_argv(self.argv)
742131
def run(*args)
      optparse(*args)

      options = {
        :env => :production,
        :host => @host,
        :port => @port
      }

      options.merge!(:server => @handler) if @handler

      App.run!(options)
    end
626361
def parse_command_line(self, argv=None):
        
        if self.config:
            parser = argparse.ArgumentParser(add_help=False)
            self.settings['config'].add_argument(parser)
            opts, _ = parser.parse_known_args(argv)
            if opts.config is not None:
                self.set('config', opts.config)

            self.params.update(self.import_from_module())

        parser = self.parser()
        opts = parser.parse_args(argv)
        for k, v in opts.__dict__.items():
            if v is None:
                continue
            self.set(k.lower(), v)