Parses the given CLI arguments to get a run configuration.
    :param args: CLI arguments
    :return: run configuration derived from the given CLI arguments
11332
def _parse_args(args: List[str]) -> _SetArgumentsRunConfig:
    
    parser = argparse.ArgumentParser(
        prog="gitlab-set-variables", description="Tool for setting a GitLab project's build variables")
    add_common_arguments(parser, project=True)
    parser.add_argument("source", nargs="+", type=str,
                        help="File to source build variables from. Can be a ini file, JSON file or a shell script "
                             "containing 'export' statements")

    arguments = parser.parse_args(args)
    return _SetArgumentsRunConfig(arguments.source, arguments.project, arguments.url, arguments.token, arguments.debug)
352270
def parse_arguments():
    
    parser = argparse.ArgumentParser()

    parser.add_argument('file', metavar="FILE", nargs='+',
                        help='file to be made executable')
    parser.add_argument("-p", "--python", metavar="VERSION",
                        help="python version (2 or 3)")
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s ' + __version__, help='show version')
    parser.add_argument('-r', '--recursive', action='store_true',
                        help='recursively iterate the directories')

    args = parser.parse_args()
    return args
1253529
def parse_args_and_run():
    
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='Docker-tag-naming sub-commands',
                                       dest='subparser_name')

    #
    #   Forge
    #
    parser_forge = subparsers.add_parser('forge',
                                         help='Create a new version tag')
    parser_forge.add_argument('--version', type=int, default=1,
                              help='Version number')
    parser_forge.add_argument('--commit-id', required=True,
                              help='Git commit id')
    parser_forge.add_argument('--branch', required=True,
                              help='The branch name (ie. master)')

    #
    #   Latest
    #
    parser_latest = subparsers.add_parser('latest',
                                          help='Query the latest tag in the'
                                               ' registry')
    parser_latest.add_argument('image',
                               help='The image to query (ie. username/image)')
    parser_latest.add_argument('branch',
                               help='The branch name (ie. master)')

    #
    #   Bump
    #
    parser_bump = subparsers.add_parser('bump',
                                        help='Query the latest tag in the'
                                             ' registry and return a +1')
    parser_bump.add_argument('image',
                             help='The image to bump (ie. username/image)')
    parser_bump.add_argument('branch',
                             help='The branch name (ie. master)')
    parser_bump.add_argument('--commit-id', required=True,
                             help='Git commit id for the newly created tag')

    #
    #   Refresh
    #
    parser_latest = subparsers.add_parser('refresh',
                                          help='Loop until the latest tag in'
                                               ' the registry changes')
    parser_latest.add_argument('image',
                               help='The image to query (ie. username/image)')
    parser_latest.add_argument('branch',
                               help='The branch name (ie. master)')

    args = parser.parse_args()

    {'bump': run_bump,
     'latest': run_latest,
     'forge': run_forge,
     'refresh': run_refresh}.get(args.subparser_name)(args)
1221945
def parse_args(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--address', help='address to listen on, default localhost',
                                default='localhost')
    parser.add_argument('-p', '--port', help='port to listen on, default 1234',
                                default=1234, type=int)
    parser.add_argument('-d', '--directory', help='directory to serve, default .',
                                default='.')
    parser.add_argument('-n', '--noindex', help='do not show directory indexes',
                                default=False, action='store_true')
    loglevel = parser.add_mutually_exclusive_group()
    loglevel.add_argument('-v', '--verbose', help='verbose logging',
                                default=False, action='store_true')
    loglevel.add_argument('-q', '--quiet', help='quiet logging',
                                default=False, action='store_true')
    return parser.parse_args(args)
506290
def get_config(cli_args=None, config_path=None):
    
    config = Config(app_name="MYAPP",
                    cli_args=cli_args,
                    config_path=config_path)
    config_dict = config.get_config()
    return config_dict
971774
def run(self, arguments=None):
        
        # set up argument parsing in run, so that subsequent calls
        # to run can call different sub-commands
        self.argparser = argparse.ArgumentParser()
        self.argparser.add_argument('--version', action='version',
                                    version="mtools version {0} || Python {1}".
                                    format(__version__, sys.version))
        self.argparser.add_argument('--no-progressbar', action='store_true',
                                    default=False,
                                    help='disables progress bar')

        self.argparser.description = ('script to launch MongoDB stand-alone '
                                      'servers, replica sets and shards.')

        # make sure init is default command even when specifying
        # arguments directly
        if arguments and arguments.startswith('-'):
            arguments = 'init ' + arguments

        # default sub-command is `init` if none provided
        elif (len(sys.argv) > 1 and sys.argv[1].startswith('-') and
                sys.argv[1] not in ['-h', '--help', '--version']):
            sys.argv = sys.argv[0:1] + ['init'] + sys.argv[1:]

        # create command sub-parsers
        subparsers = self.argparser.add_subparsers(dest='command')
        self.argparser._action_groups[0].title = 'commands'
        self.argparser._action_groups[0].description = \
            ('init is the default command and can be omitted. To get help on '
             'individual commands, run mlaunch <command> --help. Command line '
             'arguments which are not handled by mlaunch will be passed '
             'through to mongod/mongos if those options are listed in the '
             '--help output for the current binary. For example: '
             '--storageEngine, --logappend, or --config.')

        # init command
        helptext = ('initialize a new MongoDB environment and start '
                    'stand-alone instances, replica sets, or sharded '
                    'clusters.')
        desc = ('Initialize a new MongoDB environment and start stand-alone '
                'instances, replica sets, or sharded clusters. Command line '
                'arguments which are not handled by mlaunch will be passed '
                'through to mongod/mongos if those options are listed in the '
                '--help output for the current binary. For example: '
                '--storageEngine, --logappend, or --config.')
        init_parser = subparsers.add_parser('init', help=helptext,
                                            description=desc)

        # either single or replica set
        me_group = init_parser.add_mutually_exclusive_group(required=True)
        me_group.add_argument('--single', action='store_true',
                              help=('creates a single stand-alone mongod '
                                    'instance'))
        me_group.add_argument('--replicaset', action='store_true',
                              help=('creates replica set with several mongod '
                                    'instances'))

        # replica set arguments
        init_parser.add_argument('--nodes', action='store', metavar='NUM',
                                 type=int, default=3,
                                 help=('adds NUM data nodes to replica set '
                                       '(requires --replicaset, default=3)'))
        init_parser.add_argument('--arbiter', action='store_true',
                                 default=False,
                                 help=('adds arbiter to replica set '
                                       '(requires --replicaset)'))
        init_parser.add_argument('--name', action='store', metavar='NAME',
                                 default='replset',
                                 help='name for replica set (default=replset)')
        init_parser.add_argument('--priority', action='store_true',
                                 default=False,
                                 help='make lowest-port member primary')

        # sharded clusters
        init_parser.add_argument('--sharded', '--shards', action='store',
                                 nargs='+', metavar='N',
                                 help=('creates a sharded setup consisting of '
                                       'several singles or replica sets. '
                                       'Provide either list of shard names or '
                                       'number of shards.'))
        init_parser.add_argument('--config', action='store', default=-1,
                                 type=int, metavar='NUM',
                                 help=('adds NUM config servers to sharded '
                                       'setup (requires --sharded, default=1, '
                                       'with --csrs default=3)'))
        init_parser.add_argument('--csrs', default=False, action='store_true',
                                 help=('deploy config servers as a replica '
                                       'set (requires MongoDB >= 3.2.0)'))
        init_parser.add_argument('--mongos', action='store', default=1,
                                 type=int, metavar='NUM',
                                 help=('starts NUM mongos processes (requires '
                                       '--sharded, default=1)'))

        # verbose, port, binary path
        init_parser.add_argument('--verbose', action='store_true',
                                 default=False,
                                 help='outputs more verbose information.')
        init_parser.add_argument('--port', action='store', type=int,
                                 default=27017,
                                 help=('port for mongod, start of port range '
                                       'in case of replica set or shards '
                                       '(default=27017)'))
        init_parser.add_argument('--binarypath', action='store', default=None,
                                 metavar='PATH',
                                 help=('search for mongod/s binaries in the '
                                       'specified PATH.'))
        init_parser.add_argument('--dir', action='store', default='./data',
                                 help=('base directory to create db and log '
                                       'paths (default=./data/)'))
        init_parser.add_argument('--hostname', action='store',
                                 default='localhost',
                                 help=('override hostname for replica set '
                                       'configuration'))

        # authentication, users, roles
        self._default_auth_roles = ['dbAdminAnyDatabase',
                                    'readWriteAnyDatabase',
                                    'userAdminAnyDatabase',
                                    'clusterAdmin']
        init_parser.add_argument('--auth', action='store_true', default=False,
                                 help=('enable authentication and create a '
                                       'key file and admin user '
                                       '(default=user/password)'))
        init_parser.add_argument('--username', action='store', type=str,
                                 default='user',
                                 help=('username to add (requires --auth, '
                                       'default=user)'))
        init_parser.add_argument('--password', action='store', type=str,
                                 default='password',
                                 help=('password for given username (requires '
                                       '--auth, default=password)'))
        init_parser.add_argument('--auth-db', action='store', type=str,
                                 default='admin', metavar='DB',
                                 help=('database where user will be added '
                                       '(requires --auth, default=admin)'))
        init_parser.add_argument('--auth-roles', action='store',
                                 default=self._default_auth_roles,
                                 metavar='ROLE', nargs='*',
                                 help=('admin user''s privilege roles; note'
                                       'that the clusterAdmin role is '
                                       'required to run the stop command '
                                       '(requires --auth, default="%s")'
                                       % ' '.join(self._default_auth_roles)))
        init_parser.add_argument('--auth-role-docs', action='store_true',
                                 default=False,
                                 help='auth-roles are json documents')
        init_parser.add_argument('--no-initial-user', action='store_false',
                                 default=True, dest='initial-user',
                                 help=('create an initial user if auth is '
                                       'enabled (default=true)'))

        # ssl
        def is_file(arg):
            if not os.path.exists(os.path.expanduser(arg)):
                init_parser.error("The file [%s] does not exist" % arg)
            return arg

        ssl_args = init_parser.add_argument_group('SSL Options')
        ssl_args.add_argument('--sslCAFile',
                              help='Certificate Authority file for SSL',
                              type=is_file)
        ssl_args.add_argument('--sslCRLFile',
                              help='Certificate Revocation List file for SSL',
                              type=is_file)
        ssl_args.add_argument('--sslAllowInvalidHostnames',
                              action='store_true',
                              help=('allow client and server certificates to '
                                    'provide non-matching hostnames'))
        ssl_args.add_argument('--sslAllowInvalidCertificates',
                              action='store_true',
                              help=('allow client or server connections with '
                                    'invalid certificates'))

        ssl_server_args = init_parser.add_argument_group('Server SSL Options')
        ssl_server_args.add_argument('--sslOnNormalPorts', action='store_true',
                                     help='use ssl on configured ports')
        ssl_server_args.add_argument('--sslMode',
                                     help='set the SSL operation mode',
                                     choices=('disabled allowSSL preferSSL '
                                              'requireSSL'.split()))
        ssl_server_args.add_argument('--sslPEMKeyFile',
                                     help='PEM file for ssl', type=is_file)
        ssl_server_args.add_argument('--sslPEMKeyPassword',
                                     help='PEM file password')
        ssl_server_args.add_argument('--sslClusterFile',
                                     help=('key file for internal SSL '
                                           'authentication'), type=is_file)
        ssl_server_args.add_argument('--sslClusterPassword',
                                     help=('internal authentication key '
                                           'file password'))
        ssl_server_args.add_argument('--sslDisabledProtocols',
                                     help=('comma separated list of TLS '
                                           'protocols to disable '
                                           '[TLS1_0,TLS1_1,TLS1_2]'))
        ssl_server_args.add_argument('--sslWeakCertificateValidation',
                                     action='store_true',
                                     help=('allow client to connect without '
                                           'presenting a certificate'))
        ssl_server_args.add_argument(('--sslAllowConnectionsWithout'
                                      'Certificates'), action='store_true',
                                     help=('allow client to connect without '
                                           'presenting a certificate'))
        ssl_server_args.add_argument('--sslFIPSMode', action='store_true',
                                     help='activate FIPS 140-2 mode')

        ssl_client_args = init_parser.add_argument_group('Client SSL Options')
        ssl_client_args.add_argument('--sslClientCertificate',
                                     help='client certificate file for ssl',
                                     type=is_file)
        ssl_client_args.add_argument('--sslClientPEMKeyFile',
                                     help='client PEM file for ssl',
                                     type=is_file)
        ssl_client_args.add_argument('--sslClientPEMKeyPassword',
                                     help='client PEM file password')

        self.ssl_args = ssl_args
        self.ssl_client_args = ssl_client_args
        self.ssl_server_args = ssl_server_args

        # start command
        start_parser = subparsers.add_parser('start',
                                             help=('starts existing MongoDB '
                                                   'instances. Example: '
                                                   '"mlaunch start config" '
                                                   'will start all config '
                                                   'servers.'),
                                             description=('starts existing '
                                                          'MongoDB instances. '
                                                          'Example: "mlaunch '
                                                          'start config" will '
                                                          'start all config '
                                                          'servers.'))
        start_parser.add_argument('tags', metavar='TAG', action='store',
                                  nargs='*', default=[],
                                  help=('without tags, all non-running nodes '
                                        'will be restarted. Provide '
                                        'additional tags to narrow down the '
                                        'set of nodes to start.'))
        start_parser.add_argument('--verbose', action='store_true',
                                  default=False,
                                  help='outputs more verbose information.')
        start_parser.add_argument('--dir', action='store', default='./data',
                                  help=('base directory to start nodes '
                                        '(default=./data/)'))
        start_parser.add_argument('--binarypath', action='store',
                                  default=None, metavar='PATH',
                                  help=('search for mongod/s binaries in the '
                                        'specified PATH.'))

        # stop command
        helptext = ('stops running MongoDB instances. Example: "mlaunch stop '
                    'shard 2 secondary" will stop all secondary nodes '
                    'of shard 2.')
        desc = ('stops running MongoDB instances with the shutdown command. '
                'Example: "mlaunch stop shard 2 secondary" will stop all '
                'secondary nodes of shard 2.')
        stop_parser = subparsers.add_parser('stop',
                                            help=helptext,
                                            description=desc)
        helptext = ('without tags, all running nodes will be stopped. '
                    'Provide additional tags to narrow down the set of '
                    'nodes to stop.')
        stop_parser.add_argument('tags', metavar='TAG', action='store',
                                 nargs='*', default=[], help=helptext)
        stop_parser.add_argument('--verbose', action='store_true',
                                 default=False,
                                 help='outputs more verbose information.')
        stop_parser.add_argument('--dir', action='store', default='./data',
                                 help=('base directory to stop nodes '
                                       '(default=./data/)'))

        # restart command
        desc = ('stops running MongoDB instances with the shutdown command. '
                'Then restarts the stopped instances.')
        restart_parser = subparsers.add_parser('restart',
                                               help=('stops, then restarts '
                                                     'MongoDB instances.'),
                                               description=desc)
        restart_parser.add_argument('tags', metavar='TAG', action='store',
                                    nargs='*', default=[],
                                    help=('without tags, all non-running '
                                          'nodes will be restarted. Provide '
                                          'additional tags to narrow down the '
                                          'set of nodes to start.'))
        restart_parser.add_argument('--verbose', action='store_true',
                                    default=False,
                                    help='outputs more verbose information.')
        restart_parser.add_argument('--dir', action='store', default='./data',
                                    help=('base directory to restart nodes '
                                          '(default=./data/)'))
        restart_parser.add_argument('--binarypath', action='store',
                                    default=None, metavar='PATH',
                                    help=('search for mongod/s binaries in '
                                          'the specified PATH.'))

        # list command
        list_parser = subparsers.add_parser('list',
                                            help=('list MongoDB instances of '
                                                  'this environment.'),
                                            description=('list MongoDB '
                                                         'instances of this '
                                                         'environment.'))
        list_parser.add_argument('--dir', action='store', default='./data',
                                 help=('base directory to list nodes '
                                       '(default=./data/)'))
        list_parser.add_argument('--tags', action='store_true', default=False,
                                 help=('outputs the tags for each instance. '
                                       'Tags can be used to target instances '
                                       'for start/stop/kill.'))
        list_parser.add_argument('--startup', action='store_true',
                                 default=False,
                                 help=('outputs the startup command lines for '
                                       'each instance.'))
        list_parser.add_argument('--verbose', action='store_true',
                                 default=False, help='alias for --tags.')

        # list command
        helptext = ('kills (or sends another signal to) MongoDB instances '
                    'of this environment.')
        desc = ('kills (or sends another signal to) MongoDB instances '
                'of this environment.')
        kill_parser = subparsers.add_parser('kill', help=helptext,
                                            description=desc)
        kill_parser.add_argument('tags', metavar='TAG', action='store',
                                 nargs='*', default=[],
                                 help=('without tags, all running nodes will '
                                       'be killed. Provide additional tags to '
                                       'narrow down the set of nodes to '
                                       'kill.'))
        kill_parser.add_argument('--dir', action='store', default='./data',
                                 help=('base directory to kill nodes '
                                       '(default=./data/)'))
        kill_parser.add_argument('--signal', action='store', default=15,
                                 help=('signal to send to processes, '
                                       'default=15 (SIGTERM)'))
        kill_parser.add_argument('--verbose', action='store_true',
                                 default=False,
                                 help='outputs more verbose information.')

        # argparser is set up, now call base class run()
        BaseCmdLineTool.run(self, arguments, get_unknowns=True)

        # conditions on argument combinations
        if (self.args['command'] == 'init' and
                'single' in self.args and self.args['single']):
            if self.args['arbiter']:
                self.argparser.error("can't specify --arbiter for "
                                     "single nodes.")

        # replace path with absolute path, but store relative path as well
        self.relative_dir = self.args['dir']
        self.dir = os.path.abspath(self.args['dir'])
        self.args['dir'] = self.dir

        # branch out in sub-commands
        getattr(self, self.args['command'])()
393879
def load_config_from_cli_arguments(self, *args, **kwargs):
        
        self._load_config_from_cli_argument(key='handlers_package', **kwargs)
        self._load_config_from_cli_argument(key='auth', **kwargs)
        self._load_config_from_cli_argument(key='user_stream', **kwargs)
        self._load_config_from_cli_argument(key='min_seconds_between_errors', **kwargs)
        self._load_config_from_cli_argument(key='sleep_seconds_on_consecutive_errors', **kwargs)
1131347
def _load_command_line(self, conf_only=False):
        '''
        
        '''
        # did we already parse cli (i.e. to get conf file)? don't run twice
        if self._cli_opts:
            self._update_dict(self._cli_opts)
            return
        parser = argparse.ArgumentParser()
        debug_grp = parser.add_argument_group('Debug options')
        platf_grp = parser.add_argument_group('Platform options')
        cli_options = dict((k, v) for k, v in DEFAULT_OPTS.items() if (
                       'opt' in v))
        for _, o in cli_options.items():
            group = o.pop('group', None)
            if group == 'debug':
                g = debug_grp
            elif group == 'platform':
                g = platf_grp
            else:
                g = parser
            optnames = o.pop('opt')
            # use argparse.SUPPRESS as CLI defaults so it won't parse
            #  options that weren't specified
            o['default'] = argparse.SUPPRESS
            g.add_argument(*optnames, **o)

        options = parser.parse_args()

        self._cli_opts = vars(options)
        if conf_only and 'conf' in self._cli_opts:
            self._update_dict({'conf': self._cli_opts['conf']})
            return

        self._update_dict(self._cli_opts)
616756
def main(args=None):
    
    cfg.configureLogger()
    wireHandlers(cfg)
    # get config from a flask standard place not our config yml
    app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort())
1281947
def parse_cli_args():
    
    # get config paths
    home_path = os.path.expanduser("~")
    xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
    xdg_dirs_path = os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg")

    # get i3status path
    try:
        with open(os.devnull, "w") as devnull:
            command = ["which", "i3status"]
            i3status_path = (
                subprocess.check_output(command, stderr=devnull).decode().strip()
            )
    except subprocess.CalledProcessError:
        i3status_path = None

    # get window manager
    with open(os.devnull, "w") as devnull:
        if subprocess.call(["pgrep", "i3"], stdout=devnull) == 0:
            wm = "i3"
        else:
            wm = "sway"

    # i3status config file default detection
    # respect i3status' file detection order wrt issue #43
    i3status_config_file_candidates = [
        "{}/py3status/config".format(xdg_home_path),
        "{}/i3status/config".format(xdg_home_path),
        "{}/i3/i3status.conf".format(xdg_home_path),  # custom
        "{}/.i3status.conf".format(home_path),
        "{}/.i3/i3status.conf".format(home_path),  # custom
        "{}/i3status/config".format(xdg_dirs_path),
        "/etc/i3status.conf",
    ]
    for fn in i3status_config_file_candidates:
        if os.path.isfile(fn):
            i3status_config_file_default = fn
            break
    else:
        # if files does not exists, defaults to ~/.i3/i3status.conf
        i3status_config_file_default = i3status_config_file_candidates[3]

    class Parser(argparse.ArgumentParser):
        # print usages and exit on errors
        def error(self, message):
            print("\x1b[1;31merror: \x1b[0m{}".format(message))
            self.print_help()
            self.exit(1)

        # hide choices on errors
        def _check_value(self, action, value):
            if action.choices is not None and value not in action.choices:
                raise argparse.ArgumentError(
                    action, "invalid choice: '{}'".format(value)
                )

    class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
        def _format_action_invocation(self, action):
            metavar = self._format_args(action, action.dest.upper())
            return "{} {}".format(", ".join(action.option_strings), metavar)

    # command line options
    parser = Parser(
        description="The agile, python-powered, i3status wrapper",
        formatter_class=HelpFormatter,
    )
    parser.add_argument(
        "-b",
        "--dbus-notify",
        action="store_true",
        dest="dbus_notify",
        help="send notifications via dbus instead of i3-nagbar",
    )
    parser.add_argument(
        "-c",
        "--config",
        action="store",
        default=i3status_config_file_default,
        dest="i3status_config_path",
        help="load config",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="enable debug logging in syslog and --log-file",
    )
    parser.add_argument(
        "-g",
        "--gevent",
        action="store_true",
        dest="gevent",
        help="enable gevent monkey patching",
    )
    parser.add_argument(
        "-i",
        "--include",
        action="append",
        dest="include_paths",
        help="append additional user-defined module paths",
        metavar="PATH",
    )
    parser.add_argument(
        "-l",
        "--log-file",
        action="store",
        dest="log_file",
        help="enable logging to FILE",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-s",
        "--standalone",
        action="store_true",
        dest="standalone",
        help="run py3status without i3status",
    )
    parser.add_argument(
        "-t",
        "--timeout",
        action="store",
        default=60,
        dest="cache_timeout",
        help="default module cache timeout in seconds",
        metavar="INT",
        type=int,
    )
    parser.add_argument(
        "-m",
        "--disable-click-events",
        action="store_true",
        dest="disable_click_events",
        help="disable all click events",
    )
    parser.add_argument(
        "-u",
        "--i3status",
        action="store",
        default=i3status_path,
        dest="i3status_path",
        help="specify i3status path",
        metavar="PATH",
        type=str,
    )
    parser.add_argument(
        "-v",
        "--version",
        action="store_true",
        dest="print_version",
        help="show py3status version and exit",
    )
    parser.add_argument(
        "--wm",
        action="store",  # add comment to preserve formatting
        dest="wm",
        metavar="WINDOW_MANAGER",
        default=wm,
        choices=["i3", "sway"],
        help="specify window manager i3 or sway",
    )

    # deprecations
    parser.add_argument("-n", "--interval", help=argparse.SUPPRESS)

    # parse options, command, etc
    options = parser.parse_args()

    # make versions
    options.python_version = python_version()
    options.version = version
    if options.print_version:
        msg = "py3status version {version} (python {python_version}) on {wm}"
        print(msg.format(**vars(options)))
        parser.exit()

    # get wm
    options.wm_name = options.wm
    options.wm = {
        "i3": {"msg": "i3-msg", "nag": "i3-nagbar"},
        "sway": {"msg": "swaymsg", "nag": "swaynag"},
    }[options.wm]

    # make it i3status if None
    if not options.i3status_path:
        options.i3status_path = "i3status"

    # make include path to search for user modules if None
    if not options.include_paths:
        options.include_paths = [
            "{}/py3status/modules".format(xdg_home_path),
            "{}/i3status/py3status".format(xdg_home_path),
            "{}/i3/py3status".format(xdg_home_path),
            "{}/.i3/py3status".format(home_path),
        ]

    include_paths = []
    for path in options.include_paths:
        path = os.path.abspath(path)
        if os.path.isdir(path) and os.listdir(path):
            include_paths.append(path)
    options.include_paths = include_paths

    # defaults
    del options.interval
    del options.print_version
    options.minimum_interval = 0.1  # minimum module update interval
    options.click_events = not options.__dict__.pop("disable_click_events")

    # all done
    return options
368306
def get_runconfig(path=None, root=None, db=None):
    

    return load(path, root=root, db=db)
558040
def run(argv = ARGV)
      # => Parse CLI Configuration
      cli = Options.new
      cli.parse_options(argv)

      # => Grab the Default Values
      default = Config.options

      # => Parse JSON Config File (If Specified and Exists)
      json_config = Util.parse_json_config(cli.config[:config_file] || Config.config_file)

      # => Merge Configuration (CLI Wins)
      config = [default, json_config, cli.config].compact.reduce(:merge)

      # => Apply Configuration
      Config.setup do |cfg|
        cfg.config_file         = config[:config_file]
        cfg.cache_timeout       = config[:cache_timeout].to_i
        cfg.bind                = config[:bind]
        cfg.port                = config[:port]
        cfg.auth_file           = config[:auth_file]
        cfg.state_file          = config[:state_file]
        cfg.environment         = config[:environment].to_sym.downcase
        cfg.chef_api_endpoint   = config[:chef_api_endpoint]
        cfg.chef_api_client     = config[:chef_api_client]
        cfg.chef_api_client_key = config[:chef_api_client_key]
        cfg.chef_api_admin      = config[:chef_api_admin]
        cfg.chef_api_admin_key  = config[:chef_api_admin_key]
        cfg.rd_node_username    = config[:rd_node_username]
      end

      # => Launch the API
      API.run!
    end
600052
def parse_args(self, args=None, namespace=None):
        """"""
        # load the config_manager within the scope of the method that uses it
        # so that we avoid circular references in the outer scope
        from configman.config_manager import ConfigurationManager

        configuration_manager = ConfigurationManager(
            definition_source=[self.get_required_config()],
            values_source_list=self.value_source_list,
            argv_source=args,
            app_name=self.prog,
            app_version=self.version,
            app_description=self.description,
            use_auto_help=False,
        )

        # it is apparent a common idiom that commandline options may have
        # embedded '-' characters in them.  Configman requires that option
        # follow the Python Identifier rules.  Fortunately, Configman has a
        # class that will perform dynamic translation of keys.  In this
        # code fragment, we fetch the final configuration from configman
        # using a Mapping that will translate keys with '-' into keys with
        # '_' instead.
        conf = configuration_manager.get_config(
            mapping_class=create_key_translating_dot_dict(
                "HyphenUnderscoreDict",
                (('-', '_'),)
            )
        )

        # here is where we add the values given to "set_defaults" method
        # of argparse.
        if self.configman_subparsers_option:
            subparser_name = conf[self.configman_subparsers_option.name]
            try:
                conf.update(
                    self.configman_subparsers_option.foreign_data.argparse
                    .subparsers[subparser_name].subparser
                    .extra_defaults
                )
            except (AttributeError, KeyError):
                # no extra_defaults skip on
                pass

        if hasattr(self, 'extra_defaults'):
            conf.update(self.extra_defaults)

        return conf
301199
def main(args=sys.argv):
    

    parser = create_optparser(args[0])
    return cli(parser.parse_args(args[1:]))
362512
def run(args):
    
    if args is None:
        return
    
    cmd = args["commands"][0]
    if cmd == "configure":
        if len(args["commands"]) < 2:# pragma: no cover
            msg.err("'configure' command requires a second, sub-command "
                    "parameter. E.g., `acorn.py configure packages`.")
            exit(0)

        subcmd = args["commands"][1]
        _run_configure(subcmd, args)
1191026
def parse_arguments():
    
    max_procs = MAX_PROCS
    dry_run = DRY_RUN
    logging.basicConfig(level=logging.INFO, stream=sys.stdout,
                        format='%(asctime)s * %(levelname)s * %(message)s')

    parser = argparse.ArgumentParser(description="""nestrun - substitute values
            into a template and run commands in parallel.""")
    parser.add_argument('-j', '--processes', '--local', dest='local_procs',
            type=int, help="""Run a maximum of N processes in parallel locally
            (default: %(default)s)""", metavar='N', default=MAX_PROCS)
    parser.add_argument('--template', dest='template',
            metavar="'template text'", help="""Command-execution template, e.g.
            bash {infile}. By default, nestrun executes the templatefile.""")
    parser.add_argument('--stop-on-error', action='store_true',
            default=False, help="""Terminate remaining processes if any process
            returns non-zero exit status (default: %(default)s)""")
    parser.add_argument('--template-file', dest='template_file', metavar="FILE",
            help='Command-execution template file path.')
    parser.add_argument('--save-cmd-file', dest='savecmd_file',
            help="""Name of the file that will contain the command that was
            executed.""")
    log_group = parser.add_mutually_exclusive_group()
    log_group.add_argument('--log-file', dest='log_file', default='log.txt',
            help="""Name of the file that will contain output of the executed
            command.""")
    log_group.add_argument('--no-log', dest="log_file", action="store_const",
            default='log.txt', const=os.devnull, help="""Don't create a log
            file""")
    parser.add_argument('--dry-run', action='store_true', help="""Dry run mode,
            does not execute commands.""", default=False)
    parser.add_argument('--summary-file', type=argparse.FileType('w'),
            help="""Write a summary of the run to the specified file""")

    ctrl_group = parser.add_argument_group('Control files')
    ctrl_group.add_argument('json_files', metavar='control_files', type=extant_file,
            nargs='*', help="""Nestly control dictionaries""")
    ctrl_group.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    arguments = parser.parse_args()


    # Load controls
    if bool(arguments.directory) == bool(arguments.json_files):
        parser.error('Exactly one of `-d` and control_files must be specified.')
    elif arguments.directory:
        arguments.json_files.extend(control_iter(arguments.directory))

    template = arguments.template

    # Make sure that either a template or a template file was given
    if arguments.template_file:
        # if given a template file, the default is to run the input
        if not arguments.template:
            template = os.path.join('.',
                    os.path.basename(arguments.template_file))

            # If using the default argument, the template must be executable:
            if (not os.access(arguments.template_file, os.X_OK) and not
                    arguments.dry_run):
                parser.error(
                        "{0} is not executable. Specify a template.".format(
                    arguments.template_file))

    if not (arguments.template or arguments.template_file):
        parser.exit("Error: Please specify either a template "
                "or a template file")

    logging.info('Template: %s', template)

    if arguments.local_procs is not None:
        max_procs = arguments.local_procs

    # Create a dictionary that will be shared amongst all forked processes.
    data = {}
    data['dry_run'] = arguments.dry_run
    data['start_directory'] = os.getcwd()
    data['template'] = template
    data['template_file'] = arguments.template_file
    data['savecmd_file'] = arguments.savecmd_file
    data['log_file'] = arguments.log_file
    data['stop_on_error'] = arguments.stop_on_error
    data['summary_file'] = arguments.summary_file

    return data, max_procs, arguments.json_files
381412
def parse_config(args=sys.argv):
    
    parser = argparse.ArgumentParser(
        description='Read in the config file')
    parser.add_argument(
        'config_file',
        help='Configuration file.',
        metavar='FILE', type=extant_file)
    return parser.parse_args(args[1:])