Python argparse.html() Examples

The following are code examples for showing how to use argparse.html(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    (license) View Source Project 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 2
Project: ml-utils   Author: LinxiFan   File: common.py    (license) View Source Project 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 3
Project: pygeotools   Author: dshean   File: filter.py    (license) View Source Project 6 votes vote down vote up
def getparser():
    filter_choices = ['range', 'absrange', 'perc', 'gauss', 'med', 'highpass', 'sigma', 'mad', 'dz']
    parser = argparse.ArgumentParser(description='Filter input raster')
    parser.add_argument('fn', help='Input filename (img1.tif)')
    parser.add_argument('--stats', action='store_true', help='Print stats before and after filtering')
    parser.add_argument('-outdir', default=None, help='Output directory')
    #Should implement subparser here to handle different number of args for different filter types
    #https://docs.python.org/2/library/argparse.html#sub-commands
    #Can call functions directly
    #Could specify sequence of filters here
    #Should accept arbitrary number of ordered filter operations as cli argument
    parser.add_argument('-filt', nargs=1, default='gauss', choices=filter_choices, help='Filter type (default: %(default)s)')
    #size is a param
    #parser.add_argument('-size', type=int, default=7, help='Filter size in pixels (default: %(default)s)')
    parser.add_argument('-param', nargs='+', default=None, help='Filter parameter list (e.g., size, min max, ref_fn min max)')
    return parser 
Example 4
Project: biweeklybudget   Author: jantman   File: test_timings.py    (license) View Source Project 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
Project: Deploy_XXNET_Server   Author: jzp820927   File: endpointscfg.py    (license) View Source Project 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 6
Project: endpoints-python   Author: cloudendpoints   File: _endpointscfg_impl.py    (license) View Source Project 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 7
Project: climax   Author: miguelgrinberg   File: climax.py    (license) View Source Project 6 votes vote down vote up
def argument(*args, **kwargs):
    """Decorator to define an argparse option or argument.

    The arguments to this decorator are the same as the
    `ArgumentParser.add_argument <https://docs.python.org/3/library/\
argparse.html#the-add-argument-method>`_
    method.
    """
    def decorator(f):
        if not hasattr(f, '_arguments'):
            f._arguments = []
        if not hasattr(f, '_argnames'):
            f._argnames = []
        f._arguments.append((args, kwargs))
        f._argnames.append(_get_dest(*args, **kwargs))
        return f
    return decorator 
Example 8
Project: pybot   Author: spillai   File: io_utils.py    (license) View Source Project 5 votes vote down vote up
def read_config(conf_path, section): 
    """
    Recipe mostly taken from
    http://blog.vwelch.com/2011/04/combining-configparser-and-argparse.html 
    """
    # Try reading the conf file
    try: 
        import ConfigParser
        config = ConfigParser.SafeConfigParser()
        config.read([conf_path])
        defaults = dict(config.items(section))
    except Exception as e: 
        raise RuntimeError('Failed reading %s: %s' % (conf_path, e))

    return defaults 
Example 9
Project: pybot   Author: spillai   File: io_utils.py    (license) View Source Project 5 votes vote down vote up
def config_and_args_parser(conf_path, section, description=''): 
    """
    Recipe mostly taken from
    http://blog.vwelch.com/2011/04/combining-configparser-and-argparse.html 
    """
    
    # Parse directory
    parser = argparse.ArgumentParser(
        description=description)
    parser.add_argument('-c', '--config-file', required=False, 
                        default=conf_path, help='Specify config file', metavar='FILE')
    args, remaining_argv = parser.parse_known_args()

    # Try reading the conf file
    try: 
        import ConfigParser
        config = ConfigParser.SafeConfigParser()
        config.read([args.config_file])
        defaults = dict(config.items(section))
        print('Loading config file: {}'.format(args.config_file))
    except Exception as e: 
        raise RuntimeError('Failed reading %s: %s' % (args.config_file, e))

    parser.set_defaults(**defaults)
    # parser.add_argument("--option1", help="some option")
    args = parser.parse_args(remaining_argv)        
    return args 
Example 10
Project: aws-encryption-sdk-cli   Author: awslabs   File: arg_parsing.py    (Apache License 2.0) View Source Project 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) 
Example 11
Project: hostapd-mana   Author: adde88   File: config.py    (license) View Source Project 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 12
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    (license) View Source Project 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 13
Project: hgvm-builder   Author: BD2KGenomics   File: smartSam2Fastq.py    (license) View Source Project 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>
    """
    
    # 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)
    
    # General options
    parser.add_argument("--input_sam", type=argparse.FileType("r"),
        default=sys.stdin,
        help="input SAM in name-sorted order.")
    parser.add_argument("--fq1", type=argparse.FileType("w"),
        default=sys.stdout,
        help="FASTQ file to save the READ1 reads in (+READ2 if interleaved)")
    parser.add_argument("--fq2", type=argparse.FileType("w"),
        default=sys.stdout,
        help="FASTQ file to save the READ2 reads in")
    parser.add_argument("--interleaved", action="store_true",
        help="write interleaved FASTQ to fq1")
    parser.add_argument("--drop_secondary", action="store_true",
        help="drop pairs where a primary alignment is not seen at both ends")
    parser.add_argument("--expect_paired", action="store_true",
        help="expect all reads to have a pair partner and abort otherwise")
    
    # 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:]
        
    return parser.parse_args(args) 
Example 14
Project: hgvm-builder   Author: BD2KGenomics   File: importsam.py    (license) View Source Project 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>
    """
    
    # 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)
    
    # Add all the toil-vg options
    toilvgfacade.add_options(parser)
    
    # Add the Toil options so the job store is the first argument
    Job.Runner.addToilOptions(parser)
    
    parser.add_argument("--contig", default=None,
        help="download just pairs touching this contig or its alts/randoms")
    
    parser.add_argument("--sam_url", default=[], action="append",
        help="URL to download reads from, accessible from Toil nodes")
        
    # Output
    parser.add_argument("out_url",
        help="file: or other Toil-supported URL to place results in")
    
    # 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:]
        
    return parser.parse_args(args) 
Example 15
Project: hgvm-builder   Author: BD2KGenomics   File: parallelcopy.py    (license) View Source Project 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>
    """
    
    # 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)
    
    # Add the Toil options so the job store is the first argument
    Job.Runner.addToilOptions(parser)
    
    # General options
    parser.add_argument("in_store", type=IOStore.absolute,
        help="input IOStore to download from")
    parser.add_argument("out_store", type=IOStore.absolute,
        help="output IOStore to put things in")
    parser.add_argument("--pattern", default="*", 
        help="fnmatch-style pattern for file names to copy")
    parser.add_argument("--overwrite", default=False, action="store_true",
        help="overwrite existing files")
    parser.add_argument("--check_size", default=False, action="store_true",
        help="check sizes on existing files and replace if wrong")
    parser.add_argument("--batch_size", type=int, default=1000,
        help="number of files to copy in a batch")
    
    # 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:]
        
    return parser.parse_args(args) 
Example 16
Project: sslstrip-hsts-openwrt   Author: adde88   File: config.py    (license) View Source Project 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: godot-python   Author: touilleMan   File: config.py    (license) View Source Project 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: godot-python   Author: touilleMan   File: config.py    (license) View Source Project 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 19
Project: wifimitm   Author: mvondracek   File: wifimitmcli.py    (license) View Source Project 5 votes vote down vote up
def parse_args(self, args: Optional[Sequence[str]] = None):
        """
        Parse command line arguments and store checked and converted values in self.
        `"By default, the argument strings are taken from sys.argv"
            <https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_args>`_
        :type args: Optional[Sequence[str]]
        :param args: argument strings
        """
        # NOTE: Call to parse_args with namespace=self does not set logging_level with default value, if argument is not
        # in provided args, for some reason.
        parsed_args = self.parser.parse_args(args=args)

        if CommandRequirement('airmon-ng').check():
            # if airmon-ng is available, check for wireless interface name can be performed here,
            # if airmon-ng is NOT available, wifimitmcli will terminate upon requirements check after parsing args.
            # Check if provided interface name is recognized as wireless interface name.
            for i in list_wifi_interfaces():
                if i.name == parsed_args.interface.name:
                    break
            else:
                self.parser.error('argument interface: {} is not recognized as a valid wireless interface'.format(
                    parsed_args.interface.name)
                )

        # name to value conversion as noted in `self.init_parser`
        self.logging_level = self.LOGGING_LEVELS_DICT[parsed_args.logging_level]

        self.phishing_enabled = parsed_args.phishing

        if parsed_args.capture_file:
            # `"FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin
            # for readable FileType objects and sys.stdout for writable FileType objects:"
            #   <https://docs.python.org/3/library/argparse.html>`_
            if parsed_args.capture_file is sys.stdout:
                self.parser.error('argument -cf/--capture-file: stdout is not allowed')

            # The capture_file is opened by `argparse.ArgumentParser.parse_args` to make sure its writable for us.
            self.capture_file = parsed_args.capture_file

        self.essid = parsed_args.essid
        self.interface = parsed_args.interface 
Example 20
Project: basescript   Author: deep-compute   File: basescript.py    (license) View Source Project 5 votes vote down vote up
def define_subcommands(self, subcommands):
        '''
        Define subcommands (as defined at https://docs.python.org/2/library/argparse.html#sub-commands)

        eg: adding a sub-command called "blah" that invokes a function fn_blah

        blah_command = subcommands.add_parser('blah')
        blah_command.set_defaults(func=fn_blah)
        '''
        pass 
Example 21
Project: GSM-scanner   Author: yosriayed   File: config.py    (license) View Source Project 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 22
Project: climax   Author: miguelgrinberg   File: climax.py    (license) View Source Project 5 votes vote down vote up
def command(*args, **kwargs):
    """Decorator to define a command.

    The arguments to this decorator are those of the
    `ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
    object constructor.
    """
    def decorator(f):
        if 'description' not in kwargs:
            kwargs['description'] = f.__doc__
        if 'parents' in kwargs:
            if not hasattr(f, '_argnames'):  # pragma: no cover
                f._argnames = []
            for p in kwargs['parents']:
                f._argnames += p._argnames if hasattr(p, '_argnames') else []
            kwargs['parents'] = [p.parser for p in kwargs['parents']]
        f.parser = argparse.ArgumentParser(*args, **kwargs)
        f.climax = True
        for arg in getattr(f, '_arguments', []):
            f.parser.add_argument(*arg[0], **arg[1])

        @wraps(f)
        def wrapper(args=None):
            kwargs = f.parser.parse_args(args)
            return f(**vars(kwargs))

        wrapper.func = f
        return wrapper
    return decorator 
Example 23
Project: initsearchtool   Author: intel   File: isearch.py    (license) View Source Project 5 votes vote down vote up
def generate_options(self, group_parser):
        '''Adds it's options to the group parser. The parser passed in is a result from
        calling add_argument_group(ArgumentGroup): https://docs.python.org/2/library/argparse.html

        Args:
            group_parser(): The parser to add options too.

        '''
        raise NotImplementedError('Implement: generate_options') 
Example 24
Project: hgvm-builder   Author: BD2KGenomics   File: chromMatcher.py    (license) View Source Project 4 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>
    """
    
    # 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)
    
    parser.add_argument("ref_name",
        help="name of BWA-indexed reference FASTA")
    parser.add_argument("query_name",
        help="name of query FASTA")
        
    parser.add_argument("--chunk_size", type=int, default=10000,
        help="size of chunks to align")
    parser.add_argument("--chunk_stride", type=int, default=100000,
        help="distabnce between chunks to align")
    parser.add_argument("--max_children", type=int, default=10,
        help="number of bwa children to run")
    parser.add_argument("--batch_size", type=int, default=1000,
        help="number of chunks to align at once")
    parser.add_argument("--match_threshold", type=float, default=0.95,
        help="min score for a hit as a fraction of possible score")
    parser.add_argument("--out_file", type=argparse.FileType("w"),
        default=sys.stdout,
        help="TSV file of contig pairings to write")
    parser.add_argument("--debug", action="store_true",
        help="add extra debugging comments to output TSV")
    
    # 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:]
        
    return parser.parse_args(args)