Python argparse.html() Examples

The following are 30 code examples for showing how to use argparse.html(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: python-wifi-survey-heatmap   Author: jantman   File: ui.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_args(argv):
    """
    parse arguments/options

    this uses the new argparse module instead of optparse
    see: <https://docs.python.org/2/library/argparse.html>
    """
    p = argparse.ArgumentParser(description='wifi survey data collection UI')
    p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
                   help='verbose output. specify twice for debug-level output.')
    p.add_argument('INTERFACE', type=str, help='Wireless interface name')
    p.add_argument('SERVER', type=str, help='iperf3 server IP or hostname')
    p.add_argument('IMAGE', type=str, help='Path to background image')
    p.add_argument(
        'TITLE', type=str, help='Title for survey (and data filename)'
    )
    args = p.parse_args(argv)
    return args 
Example 2
def parse_args(argv):
    """
    parse arguments/options

    this uses the new argparse module instead of optparse
    see: <https://docs.python.org/2/library/argparse.html>
    """
    p = argparse.ArgumentParser(description='wifi survey heatmap generator')
    p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
                   help='verbose output. specify twice for debug-level output.')
    p.add_argument('-i', '--ignore', dest='ignore', action='append',
                   default=[], help='SSIDs to ignore from channel graph')
    p.add_argument('IMAGE', type=str, help='Path to background image')
    p.add_argument(
        'TITLE', type=str, help='Title for survey (and data filename)'
    )
    args = p.parse_args(argv)
    return args 
Example 3
Project: endpoints-python   Author: cloudendpoints   File: _endpointscfg_impl.py    License: Apache License 2.0 6 votes vote down vote up
def error(self, message):
    """Override superclass to support customized error message.

    Error message needs to be rewritten in order to display visible commands
    only, when invalid command is called by user. Otherwise, hidden commands
    will be displayed in stderr, which is not expected.

    Refer the following argparse python documentation for detailed method
    information:
      http://docs.python.org/2/library/argparse.html#exiting-methods

    Args:
      message: original error message that will be printed to stderr
    """
    # subcommands_quoted is the same as subcommands, except each value is
    # surrounded with double quotes. This is done to match the standard
    # output of the ArgumentParser, while hiding commands we don't want users
    # to use, as they are no longer documented and only here for legacy use.
    subcommands_quoted = ', '.join(
        [repr(command) for command in _VISIBLE_COMMANDS])
    subcommands = ', '.join(_VISIBLE_COMMANDS)
    message = re.sub(
        r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$'
        % subcommands, r'\1 (choose from %s)' % subcommands_quoted, message)
    super(_EndpointsParser, self).error(message) 
Example 4
Project: biweeklybudget   Author: jantman   File: test_timings.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_args(argv):
    """
    parse arguments/options

    this uses the new argparse module instead of optparse
    see: <https://docs.python.org/2/library/argparse.html>
    """
    p = argparse.ArgumentParser(description='Report on test run timings')
    p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
                   help='verbose output. specify twice for debug-level output.')
    c = ['acceptance36', 'acceptance27']
    p.add_argument('-j', '--jobtype', dest='jobtype', action='store', type=str,
                   choices=c, default=c[0], help='TOXENV for job')
    p.add_argument('BUILD_NUM', action='store', type=str, nargs='?',
                   default=None,
                   help='TravisCI X.Y build number to analyze; if not '
                        'specified, will use latest acceptance36 build.')
    args = p.parse_args(argv)
    return args 
Example 5
def arg_parse_params():
    """ argument parser from cmd

    :return dict:
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--path_annots', type=str, required=False,
                        help='path to folder with annotations')
    parser.add_argument('-d', '--path_dataset', type=str, required=False,
                        help='path to the output directory - dataset')
    parser.add_argument('--scales', type=int, required=False, nargs='*',
                        help='generated scales for the dataset', default=DEFAULT_SCALES)
    parser.add_argument('--nb_selected', type=float, required=False, default=None,
                        help='number ot ration of selected landmarks')
    parser.add_argument('--nb_total', type=int, required=False, default=None,
                        help='total number of generated landmarks')
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes in parallel')
    args = parse_arg_params(parser)
    if not is_iterable(args['scales']):
        args['scales'] = [args['scales']]
    return args 
Example 6
Project: BIRL   Author: Borda   File: experiments.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_arg_params(parser, upper_dirs=None):
    """ parse all params

    :param parser: object of parser
    :param list(str) upper_dirs: list of keys in parameters
        with item for which only the parent folder must exist
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    args = vars(parser.parse_args())
    logging.info('ARGUMENTS: \n %r', args)
    # remove all None parameters
    args = {k: args[k] for k in args if args[k] is not None}
    # extend and test all paths in params
    args, missing = update_paths(args, upper_dirs=upper_dirs)
    assert not missing, 'missing paths: %r' % {k: args[k] for k in missing}
    return args 
Example 7
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_commands(self):
        """
        Split up the functionality of nrfjprog into multiple sub-commands.

        :param Object subparsers: https://docs.python.org/3/library/argparse.html#sub-commands.
        """
        self._add_erase_command()
        self._add_halt_command()
        self._add_ids_command()
        self._add_memrd_command()
        self._add_memwr_command()
        self._add_pinresetenable_command()
        self._add_program_command()
        self._add_readback_command()
        self._add_readregs_command()
        self._add_readtofile_command()
        self._add_recover_command()
        self._add_reset_command()
        self._add_run_command()
        self._add_verify_command()
        self._add_version_command()

    # The top-level positional commands of our command-line interface. 
Example 8
def arg_parse_params():
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return dict:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-imgs', '--path_images', type=str, required=False,
                        help='path to dir and image pattern', default=PATH_IMAGES)
    parser.add_argument('-csv', '--path_csv', type=str, required=False,
                        help='path to the CSV directory', default=PATH_CSV)
    parser.add_argument('-info', '--path_info', type=str, required=False,
                        help='path to file with complete info', default=None)
    params = vars(parser.parse_args())
    for k in (k for k in params if 'path' in k):
        if not params[k]:
            continue
        params[k] = os.path.abspath(os.path.expanduser(params[k]))
        p = os.path.dirname(params[k]) if '*' in params[k] else params[k]
        assert os.path.exists(p), 'missing: %s' % p
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 9
def arg_parse_params():
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return {str: str}:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-annot', '--path_annot', type=str, required=False,
                        help='path to directory & name pattern for annotations',
                        default=PATH_ANNOT)
    parser.add_argument('-out', '--path_out', type=str, required=False,
                        help='path to the output directory', default=PATH_DATA)
    parser.add_argument('-nb', '--nb_comp', type=int, required=False,
                        help='number of component in Mixture model', default=2)
    params = vars(parser.parse_args())
    for k in (k for k in params if 'path' in k):
        params[k] = tl_data.update_path(params[k], absolute=True)
        p = os.path.dirname(params[k]) if k == 'path_annot' else params[k]
        assert os.path.exists(p), 'missing: %s' % p
    # load saved configuration
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 10
Project: ClusterRunner   Author: box   File: argument_parsing.py    License: Apache License 2.0 6 votes vote down vote up
def _get_option_tuples(self, option_string):
        """
        This method is overridden explicitly to disable argparse prefix matching. Prefix matching is an undesired
        default behavior as it creates the potential for unintended breaking changes just by adding a new command-line
        argument.

        For example, if a user uses the argument "--master" to specify a value for "--master-url", and later we add a
        new argument named "--master-port", that change will break the user script that used "--master".

        See: https://docs.python.org/3.4/library/argparse.html#argument-abbreviations-prefix-matching
        """
        # This if statement comes from the superclass implementation -- it precludes a code path in the superclass
        # that is responsible for checking for argument prefixes. The return value of an empty list is the way that
        # this method communicates no valid arguments were found.
        chars = self.prefix_chars
        if option_string[0] in chars and option_string[1] in chars:
            return []

        return super()._get_option_tuples(option_string) 
Example 11
Project: abseil-py   Author: abseil   File: argparse_flags.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
    """See https://docs.python.org/3/library/argparse.html#action-classes."""
    # This only prints flags when help is not argparse.SUPPRESS.
    # It includes user defined argparse flags, as well as main module's
    # key absl flags. Other absl flags use argparse.SUPPRESS, so they aren't
    # printed here.
    parser.print_help()

    absl_flags = parser._inherited_absl_flags  # pylint: disable=protected-access
    if absl_flags:
      modules = sorted(absl_flags.flags_by_module_dict())
      main_module = sys.argv[0]
      if main_module in modules:
        # The main module flags are already printed in parser.print_help().
        modules.remove(main_module)
      print(absl_flags._get_help_for_modules(  # pylint: disable=protected-access
          modules, prefix='', include_special_flags=True))
    parser.exit() 
Example 12
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: endpointscfg.py    License: Apache License 2.0 6 votes vote down vote up
def error(self, message):
    """Override superclass to support customized error message.

    Error message needs to be rewritten in order to display visible commands
    only, when invalid command is called by user. Otherwise, hidden commands
    will be displayed in stderr, which is not expected.

    Refer the following argparse python documentation for detailed method
    information:
      http://docs.python.org/2/library/argparse.html#exiting-methods

    Args:
      message: original error message that will be printed to stderr
    """




    subcommands_quoted = ', '.join(
        [repr(command) for command in _VISIBLE_COMMANDS])
    subcommands = ', '.join(_VISIBLE_COMMANDS)
    message = re.sub(
        r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$'
        % subcommands, r'\1 (choose from %s)' % subcommands_quoted, message)
    super(_EndpointsParser, self).error(message) 
Example 13
Project: surreal   Author: SurrealAI   File: common.py    License: MIT License 6 votes vote down vote up
def add(self, *args, **kwargs):
        default = kwargs.get('default')
        dtype = kwargs.get('type')
        if dtype is None:
            if default is None:
                dtype = str
            else:
                dtype = type(default)
        typename = dtype.__name__
        if 'metavar' not in kwargs:
            # metavar: display --foo <float=0.05> in help string
            if 'choices' in kwargs:
                choices = kwargs['choices']
                choices_str = '/'.join(['{}']*len(choices)).format(*choices)
                kwargs['metavar'] = '<{}: {}>'.format(typename, choices_str)
            elif 'nargs' in kwargs:
                # better formatting handled in _SingleMetavarFormatter
                kwargs['metavar'] = '{}'.format(typename)
            elif not kwargs.get('action'):
                # if 'store_true', then no metavar needed
                # list of actions: https://docs.python.org/3/library/argparse.html#action
                default_str = '={}'.format(default) if default else ''
                kwargs['metavar'] = '<{}{}>'.format(typename, default_str)
        self.parser.add_argument(*args, **kwargs) 
Example 14
Project: GelReportModels   Author: genomicsengland   File: avdlDoxyFilter.py    License: Apache License 2.0 5 votes vote down vote up
def parse_args(args):
    """
    Takes in the command-line arguments list (args), and returns a nice argparse
    result with fields for all the options.
    Borrows heavily from the argparse documentation examples:
    <http://docs.python.org/library/argparse.html>
    """

    # The command line arguments start with the program name, which we don't
    # want to treat as an argument for argparse. So we remove it.
    args = args[1:]

    # Construct the parser (which is stored in parser)
    # Module docstring lives in __doc__
    # See http://python-forum.com/pythonforum/viewtopic.php?f=3&t=36847
    # And a formatter class so our examples in the docstring look good. Isn't it
    # convenient how we already wrapped it to 80 characters?
    # See http://docs.python.org/library/argparse.html#formatter-class
    parser = argparse.ArgumentParser(description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    # Now add all the options to it
    parser.add_argument("avdl", type=argparse.FileType('r'),
        help="the AVDL file to read")

    return parser.parse_args(args) 
Example 15
def parse_args(argv):
    """
    parse arguments/options

    this uses the new argparse module instead of optparse
    see: <https://docs.python.org/2/library/argparse.html>
    """
    p = argparse.ArgumentParser(description='wifi scan CLI')
    p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
                   help='verbose output. specify twice for debug-level output.')
    p.add_argument('INTERFACE', type=str, help='Wireless interface name')
    p.add_argument('SERVER', type=str, help='iperf3 server IP or hostname')
    args = p.parse_args(argv)
    return args 
Example 16
Project: python-netsurv   Author: sofia-netsurv   File: argparsing.py    License: MIT License 5 votes vote down vote up
def addoption(self, *opts, **attrs):
        """ register a command line option.

        :opts: option names, can be short or long options.
        :attrs: same attributes which the ``add_option()`` function of the
           `argparse library
           <http://docs.python.org/2/library/argparse.html>`_
           accepts.

        After command line parsing options are available on the pytest config
        object via ``config.option.NAME`` where ``NAME`` is usually set
        by passing a ``dest`` attribute, for example
        ``addoption("--long", dest="NAME", ...)``.
        """
        self._anonymous.addoption(*opts, **attrs) 
Example 17
Project: python-netsurv   Author: sofia-netsurv   File: argparsing.py    License: MIT License 5 votes vote down vote up
def addoption(self, *opts, **attrs):
        """ register a command line option.

        :opts: option names, can be short or long options.
        :attrs: same attributes which the ``add_option()`` function of the
           `argparse library
           <http://docs.python.org/2/library/argparse.html>`_
           accepts.

        After command line parsing options are available on the pytest config
        object via ``config.option.NAME`` where ``NAME`` is usually set
        by passing a ``dest`` attribute, for example
        ``addoption("--long", dest="NAME", ...)``.
        """
        self._anonymous.addoption(*opts, **attrs) 
Example 18
Project: BIRL   Author: Borda   File: evaluate_submission.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_parser():
    """ parse the input parameters
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('-e', '--path_experiment', type=str, required=True,
                        help='path to the experiments', default='/input/')
    parser.add_argument('-t', '--path_table', type=str, required=True,
                        help='path to cover table (csv file)',
                        default='/opt/evaluation/dataset.csv')
    parser.add_argument('-d', '--path_dataset', type=str, required=True,
                        help='path to dataset with provided landmarks',
                        default='/opt/evaluation/provided')
    parser.add_argument('-r', '--path_reference', type=str, required=False,
                        help='path to complete ground truth landmarks')
    parser.add_argument('-p', '--path_comp_bm', type=str, required=False,
                        help='path to reference computer performance JSON')
    parser.add_argument('-o', '--path_output', type=str, required=True,
                        help='path to output results', default='/output/')
    # required number of submitted landmarks, match values in COL_PAIRED_LANDMARKS
    parser.add_argument('--min_landmarks', type=float, required=False, default=0.5,
                        help='ration of required landmarks in submission')
    # parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
    #                     help='number of processes in parallel')
    parser.add_argument('--details', action='store_true', required=False,
                        default=False, help='export details for each case')
    return parser 
Example 19
Project: BIRL   Author: Borda   File: evaluate_experiment.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_parser():
    """ parse the input parameters
    :return dict: {str: any}
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('-e', '--path_experiment', type=str, required=True,
                        help='path to the experiments')
    parser.add_argument('-d', '--path_dataset', type=str, required=False,
                        help='path to dataset with provided landmarks')
    parser.add_argument('--visual', action='store_true', required=False,
                        default=False, help='visualise the landmarks in images')
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes running in parallel')
    return parser 
Example 20
Project: BIRL   Author: Borda   File: bm_comp_perform.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params():
    """ parse the input parameters
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--path_out', type=str, required=False,
                        help='path to the output folder', default='')
    parser.add_argument('-n', '--nb_runs', type=int, required=False,
                        help='number of run experiments', default=5)
    args = vars(parser.parse_args())
    logging.info('ARGUMENTS: \n%r' % args)
    return args 
Example 21
def arg_parse_params():
    """ parse the input parameters
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('--dimension', type=int, required=False, choices=[0, 1],
                        help='cutting dimension', default=CUT_DIMENSION)
    args = args_expand_parse_images(parser, NB_WORKERS)
    logging.info('ARGUMENTS: \n%r' % args)
    return args 
Example 22
Project: BIRL   Author: Borda   File: convert_tiff2png.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params():
    """ parse the input parameters
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--level', type=int, required=False,
                        help='list of output scales', default=DEFAULT_LEVEL)
    args = args_expand_parse_images(parser, NB_WORKERS)
    logging.info('ARGUMENTS: \n%r' % args)
    return args 
Example 23
Project: BIRL   Author: Borda   File: rescale_tissue_images.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params():
    """ parse the input parameters
    :return dict: parameters
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('--scales', type=int, required=False, nargs='+',
                        help='list of output scales', default=DEFAULT_SCALES)
    parser.add_argument('-ext', '--image_extension', type=str, required=False,
                        help='output image extension', default=IMAGE_EXTENSION)
    args = args_expand_parse_images(parser, NB_WORKERS)
    if not is_iterable(args['scales']):
        args['scales'] = [args['scales']]
    logging.info('ARGUMENTS: \n%r' % args)
    return args 
Example 24
Project: BIRL   Author: Borda   File: crop_tissue_images.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params():
    """ parse the input parameters
    :return dict: {str: any}
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser()
    parser.add_argument('--padding', type=float, required=False, default=0.1,
                        help='padding around the object in image percents')
    args = args_expand_parse_images(parser, NB_WORKERS, overwrite=False)
    logging.info('ARGUMENTS: \n%r' % args)
    return args 
Example 25
Project: BIRL   Author: Borda   File: experiments.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_basic_parser(name=''):
    """ create the basic arg parses

    :param str name: name of the methods
    :return object:

    >>> parser = create_basic_parser()
    >>> type(parser)
    <class 'argparse.ArgumentParser'>
    >>> parse_arg_params(parser)  # doctest: +SKIP
    """
    # SEE: https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser('Benchmark on Image Registration - %s' % name)
    parser.add_argument('-n', '--name', type=str, required=False, default=None,
                        help='custom experiment name')
    parser.add_argument('-t', '--path_table', type=str, required=True,
                        help='path to the csv cover file')
    parser.add_argument('-d', '--path_dataset', type=str, required=False, default=None,
                        help='path to the dataset location, if missing in table')
    parser.add_argument('-o', '--path_out', type=str, required=True,
                        help='path to the output directory')
    parser.add_argument('--unique', dest='unique', action='store_true',
                        help='whether each experiment have unique time stamp')
    parser.add_argument('--visual', dest='visual', action='store_true',
                        help='whether visualise partial results')
    parser.add_argument('-pproc', '--preprocessing', type=str, required=False, nargs='+',
                        help='use some image pre-processing, the other matter',
                        choices=['gray'] + ['matching-%s' % clr for clr in CONVERT_RGB])
    # parser.add_argument('--lock_expt', dest='lock_thread', action='store_true',
    #                     help='whether lock to run experiment in single thread')
    parser.add_argument('--run_comp_benchmark', action='store_true',
                        help='run computation benchmark on the end')
    parser.add_argument('--nb_workers', type=int, required=False, default=1,
                        help='number of registration running in parallel')
    return parser 
Example 26
Project: pytest   Author: pytest-dev   File: argparsing.py    License: MIT License 5 votes vote down vote up
def addoption(self, *opts: str, **attrs: Any) -> None:
        """ register a command line option.

        :opts: option names, can be short or long options.
        :attrs: same attributes which the ``add_argument()`` function of the
           `argparse library
           <https://docs.python.org/library/argparse.html>`_
           accepts.

        After command line parsing options are available on the pytest config
        object via ``config.option.NAME`` where ``NAME`` is usually set
        by passing a ``dest`` attribute, for example
        ``addoption("--long", dest="NAME", ...)``.
        """
        self._anonymous.addoption(*opts, **attrs) 
Example 27
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    """
    Set up a command line interface using the argparse module.

    Above we will define what arguments our program requires and argparse will figure out how to parse those from sys.argv.
    For info on argparse see: https://docs.python.org/3/library/argparse.html.
    """
    cli = Nrfjprog()
    cli.run() 
Example 28
Project: You-are-Pythonista   Author: MiracleYoung   File: ssh_execute_concurrent.py    License: GNU General Public License v3.0 5 votes vote down vote up
def argument(self):
        '''
        利用argparse这个模块,自定义脚本的命令行参数
        需要模块用法的请参见:https://blog.ixxoo.me/argparse.html
        '''
        parse = argparse.ArgumentParser()
        # 定义需要执行的线程数参数:-t
        parse.add_argument('--thread-number', '-t', dest='num_value', help='thread number')
        # 定义需要执行的命令行参数:-c
        parse.add_argument('--command-line', '-c', dest='cmd_value', help='command line')
        args = parse.parse_args()
        # 返回args对象
        return args 
Example 29
Project: You-are-Pythonista   Author: MiracleYoung   File: ssh_execute_concurrent.py    License: GNU General Public License v3.0 5 votes vote down vote up
def main(self, cmd, method, thread_num=1):
        '''
        最终实现逻辑的主函数
        '''
        # 获取最终存在的服务器更新列表
        self.update_hosts = self.get_exists_host()
        try:
            # linux命令行上执行时输出打印信息(让脚本使用者能看的清楚明了)
            r = raw_input('本次需要更新以下服务器:{},服务器数量:{},服务器更新命令:{},确认按1:'.format(self.host_lists,len(self.update_hosts),cmd))
            # 判断用户输入是否合法,输入不合法退出程序
            if len(r) ==  1 and r.isdigit() and int(r) == 1:
                    pass
            else:
                return False
        except:
            print
            return False
        obj_dict = dict()
        total_host = len(self.update_hosts)
        current_hostname = 1
        # 进度条相关处理,具体用法可以参见http://www.cnblogs.com/hongfei/p/3982259.html(这个讲的比较好,还有动图)
        progress = ProgressBar()
        proceed_progress = progress(range(total_host))

# 多线程相关处理,具体用法可以参见
# 这里创建了线程池,max_workers是默认的处理线程个数
# 参见https://docs.python.org/3/library/concurrent.futures.html 
Example 30
Project: aws-encryption-sdk-cli   Author: aws   File: arg_parsing.py    License: Apache License 2.0 5 votes vote down vote up
def add_argument(self, *args, **kwargs):
        # The type profile for this it really complex and we don't do anything substantive
        # to it, so I would rather not duplicate the typeshed's effort keeping it up to date.
        # https://github.com/python/typeshed/blob/master/stdlib/2and3/argparse.pyi#L53-L65
        """Adds the requested argument to the parser, also adding a dummy redirect argument
        if a long-form argument (starts with two starting prefix characters) is found.

        See: https://docs.python.org/dev/library/argparse.html#the-add-argument-method
        """
        for long_arg in [arg for arg in args if arg.startswith(self.prefix_chars * 2)]:
            self.add_dummy_redirect_argument(long_arg)

        return super(CommentIgnoringArgumentParser, self).add_argument(*args, **kwargs)