Python argparse.html() Examples

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

Example 1
Project: decli   Author: Woile   File: examples.py    MIT License 6 votes vote down vote up
def main_example():
    """https://docs.python.org/3/library/argparse.html#example"""
    data = {
        "description": "Process some integers.",
        "arguments": [
            {
                "name": "integers",
                "metavar": "N",
                "type": int,
                "nargs": "+",
                "help": "an integer for the accumulator",
            },
            {
                "name": "--sum",
                "dest": "accumulate",
                "action": "store_const",
                "const": sum,
                "default": max,
                "help": "sum the integers (default: find the max)",
            },
        ],
    }
    parser = cli(data)
    return parser 
Example 2
Project: decli   Author: Woile   File: examples.py    MIT License 6 votes vote down vote up
def compose_clis_using_parents():
    """
    Sometimes, several cli share a common set of arguments.
    Rather than repeating the definitions of these arguments,
    one or more parent clis with all the shared arguments can be passed
    to parents= argument to cli.

    https://docs.python.org/3/library/argparse.html#parents
    """
    parent_foo_data = {
        "add_help": False,
        "arguments": [{"name": "--foo-parent", "type": int}],
    }
    parent_bar_data = {
        "add_help": False,
        "arguments": [{"name": "--bar-parent", "type": int}],
    }
    parent_foo_cli = cli(parent_foo_data)
    parent_bar_cli = cli(parent_bar_data)

    parents = [parent_foo_cli, parent_bar_cli]
    return parents 
Example 3
Project: decli   Author: Woile   File: examples.py    MIT License 6 votes vote down vote up
def using_formatter_class():
    """https://docs.python.org/3/library/argparse.html#formatter-class"""
    data = {
        "prog": "PROG",
        "formatter_class": argparse.RawDescriptionHelpFormatter,
        "description": textwrap.dedent(
            """\
            Please do not mess up this text!
            --------------------------------
                I have indented it
                exactly the way
                I want it
            """
        ),
    }
    return data 
Example 4
Project: python-wifi-survey-heatmap   Author: jantman   File: ui.py    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 5
Project: python-wifi-survey-heatmap   Author: jantman   File: heatmap.py    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 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 6
Project: biweeklybudget   Author: jantman   File: test_timings.py    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 7
Project: safitty   Author: catalyst-team   File: parser.py    MIT License 6 votes vote down vote up
def argparser(**argparser_kwargs) -> argparse.ArgumentParser:
    """Creates typical argument parser with ``--config`` argument
    Args:
        **argparser_kwargs: Arguments for ``ArgumentParser.__init__``, optional.
            See more at `Argparse docs`_
    Returns:
        (ArgumentParser): parser with ``--config`` argument

    .. _`Argparse docs`:
        https://docs.python.org/3/library/argparse.html#argumentparser-objects
    """
    argparser_kwargs = argparser_kwargs
    parser_ = argparse.ArgumentParser(**argparser_kwargs)

    parser_.add_argument(
        "-C", "--config", "--configs",
        nargs="+",
        required=True,
        dest="configs",
        help="Path to a config file/files (YAML or JSON)",
        metavar="{PATH}"
    )
    return parser_ 
Example 8
Project: BIRL   Author: Borda   File: rescale_tissue_landmarks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 9
Project: BIRL   Author: Borda   File: experiments.py    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 10
Project: mapscookiegettercli   Author: costastf   File: mapscookiegettercli.py    MIT License 6 votes vote down vote up
def get_arguments():
    """
    Gets us the cli arguments.

    Returns the args as parsed from the argsparser.
    """
    # https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser(description='''A tool to retrieve the cookies from a google authentication process
                                                    towards the google maps service to be used with locationsharinglib.
                                                    ''')
    parser.add_argument('--log-level',
                        '-L',
                        help='Provide the log level. Defaults to info.',
                        dest='log_level',
                        action='store',
                        type=str.upper,
                        default='INFO',
                        choices=['DEBUG',
                                 'INFO',
                                 'WARNING',
                                 'ERROR',
                                 'CRITICAL'])
    args = parser.parse_args()
    return args 
Example 11
Project: climax   Author: miguelgrinberg   File: climax.py    MIT License 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 12
Project: dataset-histology-landmarks   Author: Borda   File: run_visualise_landmarks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_arg_parser():
    """ argument parser from cmd

    SEE: https://docs.python.org/3/library/argparse.html
    :return {str: ...}:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--path_landmarks', type=str, required=False,
                        help='path to folder with landmarks (particular scale)',
                        default='dataset')
    parser.add_argument('-i', '--path_dataset', type=str, required=False,
                        help='path to folder with dataset (images)',
                        default='dataset')
    parser.add_argument('-o', '--path_output', type=str, required=False,
                        help='path to the output directory - visualisation',
                        default='output')
    parser.add_argument('--scales', type=int, required=False, nargs='*',
                        help='select scales for visualization', default=None)
    parser.add_argument('--nb_jobs', type=int, required=False, default=NB_THREADS,
                        help='number of processes in parallel')
    return parser 
Example 13
Project: dataset-histology-landmarks   Author: Borda   File: run_evaluate_landmarks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_arg_parser():
    """ argument parser from cmd

    SEE: https://docs.python.org/3/library/argparse.html
    :return {str: ...}:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--path_annots', type=str, required=False,
                        help='path to folder with annotations',
                        default='annotations')
    parser.add_argument('-i', '--path_dataset', type=str, required=False,
                        help='path to folder with dataset (images)',
                        default='dataset')
    parser.add_argument('-o', '--path_output', type=str, required=False,
                        help='path to the output directory - visualisation',
                        default='output')
    parser.add_argument('--consensus', type=str, required=False,
                        help='method for consensus landmarks',
                        choices=['mean', 'median'], default='mean')
    parser.add_argument('--visual', required=False, action='store_true',
                        help='export co-annotation visualisation', default=False)
    parser.add_argument('--nb_jobs', type=int, required=False,
                        help='number of processes in parallel',
                        default=NB_THREADS)
    return parser 
Example 14
Project: dataset-histology-landmarks   Author: Borda   File: run_generate_landmarks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_arg_parser():
    """ argument parser from cmd

    SEE: https://docs.python.org/3/library/argparse.html
    :return {str: ...}:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--path_annots', type=str, required=False,
                        help='path to folder with annotations',
                        default='annotations')
    parser.add_argument('-d', '--path_dataset', type=str, required=False,
                        help='path to the output directory - dataset',
                        default='dataset')
    parser.add_argument('--scales', type=int, required=False, nargs='*',
                        help='generated scales for the dataset', default=SCALES)
    parser.add_argument('--consensus', type=str, required=False,
                        help='method for consensus landmarks',
                        choices=['mean', 'median'], default='mean')
    parser.add_argument('--nb_jobs', type=int, required=False,
                        help='number of processes in parallel',
                        default=NB_THREADS)
    return parser 
Example 15
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    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 16
Project: pygeotools   Author: dshean   File: filter.py    MIT License 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 17
Project: pyImSegm   Author: Borda   File: gui_annot_center_correction.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 18
Project: pyImSegm   Author: Borda   File: run_RG2Sp_estim_shape-models.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 19
Project: abseil-py   Author: abseil   File: argparse_flags.py    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 20
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: endpointscfg.py    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 21
Project: checkmk-collector   Author: finalduty   File: agent.py    MIT License 6 votes vote down vote up
def main():
    ## Parse CommandLine arguments
    ## https://docs.python.org/2/howto/argparse.html
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--daemonize", action="store_true", help="Run in background")
    parser.add_argument("-v", "--verbose", action="store_true", help="Run verbosely")
    args = parser.parse_args()
    
    ## If daemonize=True, run in loop
    if args.daemonize:
        while True:
            send_status(get_status())
            sleep(15 + randint(-3,3))
    ## Otherwise, run once and exit
    else:
        send_status(get_status())

    exit(0) 
Example 22
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: argparse_flags.py    GNU General Public License v3.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 23
Project: decli   Author: Woile   File: examples.py    MIT License 5 votes vote down vote up
def name_or_flags():
    """https://docs.python.org/3/library/argparse.html#name-or-flags"""
    data = {
        "prog": "sti",
        "arguments": [{"name": ["-f", "--foo"]}, {"name": "bar"}],
    }
    return data 
Example 24
Project: python-wifi-survey-heatmap   Author: jantman   File: scancli.py    GNU Affero General Public License v3.0 5 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 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 25
Project: Alexa-Ecovacs   Author: EtienneMD   File: config.py    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 26
Project: python-netsurv   Author: sofia-netsurv   File: argparsing.py    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 27
Project: python-netsurv   Author: sofia-netsurv   File: argparsing.py    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 28
Project: 2019-1-OSS-L1   Author: 19-1-skku-oss   File: argparsing.py    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 29
Project: yaani   Author: Cloud-Temple   File: yaani.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_cli_args(script_args):
    """Declare and configure script argument parser

    Args:
            script_args (list): The list of script arguments

    Returns:
            obj: The parsed arguments in an object. See argparse documention
                 (https://docs.python.org/3.7/library/argparse.html)
                 for more information.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-c', '--config-file',
        default=os.getenv(
            DEFAULT_ENV_CONFIG_FILE, os.getcwd() + "/netbox.yml"
        ),
        help="""Path for script's configuration file. If None is specified,
                default value is %s environment variable or netbox.yml in the
                current dir.""" % DEFAULT_ENV_CONFIG_FILE
    )
    parser.add_argument(
        '--list', action='store_true', default=False,
        help="""Print the entire inventory with hostvars respecting
                the Ansible dynamic inventory syntax."""
    )
    parser.add_argument(
        '--host', action='store', default=None,
        help="""Print specific host vars as Ansible dynamic
                inventory syntax."""
    )

    # Parse script arguments and return the result
    return parser.parse_args(script_args) 
Example 30
Project: BIRL   Author: Borda   File: evaluate_submission.py    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 31
Project: BIRL   Author: Borda   File: evaluate_experiment.py    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 32
Project: BIRL   Author: Borda   File: bm_comp_perform.py    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 33
Project: BIRL   Author: Borda   File: split_images_two_tissues.py    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('--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 34
Project: BIRL   Author: Borda   File: convert_tiff2png.py    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 35
Project: BIRL   Author: Borda   File: rescale_tissue_images.py    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 36
Project: BIRL   Author: Borda   File: crop_tissue_images.py    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 37
Project: BIRL   Author: Borda   File: experiments.py    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 38
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: unixcommand.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, prog, description="", epilog="", command=None, **kwargs):
        """
        Build a UnixCommandParser with a link to the command using it.

        Args:
            prog (str): the program name (usually the command key).
            description (str): a very brief line to show in the usage text.
            epilog (str): the epilog to show below options.
            command (Command): the command calling the parser.

        Kwargs:
            Additional keyword arguments are directly sent to
            `argparse.ArgumentParser`.  You will find them on the
            [parser's documentation](https://docs.python.org/2/library/argparse.html).

        Note:
            It's doubtful you would need to create this parser manually.
            The `UnixCommand` does that automatically.  If you create
            sub-commands, this class will be used.

        """
        prog = prog or command.key
        super(UnixCommandParser, self).__init__(
            prog=prog, description=description,
            conflict_handler='resolve', add_help=False, **kwargs)
        self.command = command
        self.post_help = epilog

        def n_exit(code=None, msg=None):
            raise ParseError(msg)

        self.exit = n_exit

        # Replace the -h/--help
        self.add_argument("-h", "--hel", nargs=0, action=HelpAction,
                          help="display the command help") 
Example 39
Project: encarnia   Author: whitehorse-io   File: unixcommand.py    MIT License 5 votes vote down vote up
def __init__(self, prog, description="", epilog="", command=None, **kwargs):
        """
        Build a UnixCommandParser with a link to the command using it.

        Args:
            prog (str): the program name (usually the command key).
            description (str): a very brief line to show in the usage text.
            epilog (str): the epilog to show below options.
            command (Command): the command calling the parser.

        Kwargs:
            Additional keyword arguments are directly sent to
            `argparse.ArgumentParser`.  You will find them on the
            [parser's documentation](https://docs.python.org/2/library/argparse.html).

        Note:
            It's doubtful you would need to create this parser manually.
            The `UnixCommand` does that automatically.  If you create
            sub-commands, this class will be used.

        """
        prog = prog or command.key
        super(UnixCommandParser, self).__init__(
                prog=prog, description=description,
                conflict_handler='resolve', add_help=False, **kwargs)
        self.command = command
        self.post_help = epilog

        def n_exit(code=None, msg=None):
            raise ParseError(msg)

        self.exit = n_exit

        # Replace the -h/--help
        self.add_argument("-h", "--hel", nargs=0, action=HelpAction,
                          help="display the command help") 
Example 40
Project: autosimulationcraft   Author: jantman   File: runner.py    GNU Affero General Public License v3.0 5 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='A python script to run SimulationCraft '
                                'reports for World of Warcraft characters when their '
                                'gear/stats/level/etc. changes.')
    p.add_argument('-d', '--dry-run', dest='dry_run', action='store_true', default=False,
                   help="dry-run - don't send email, just say what would be sent")
    p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
                   help='verbose output. specify twice for debug-level output.')
    p.add_argument('-c', '--configdir', dest='confdir', action='store',
                   type=str, default=DEFAULT_CONFDIR,
                   help='configuration directory (default: {c})'.format(c=DEFAULT_CONFDIR))
    p.add_argument('-s', '--no-stat', dest='no_stat', action='store_true', default=False,
                   help='ignore overall stats when determining if character changed')
    p.add_argument('--genconfig', dest='genconfig', action='store_true', default=False,
                   help='generate a sample configuration file at configdir/settings.py')
    p.add_argument('--version', dest='version', action='store_true', default=False,
                   help='print version number and exit.')
    args = p.parse_args(argv)

    return args 
Example 41
Project: climax   Author: miguelgrinberg   File: climax.py    MIT License 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 42
Project: clams   Author: unbservices   File: __init__.py    MIT License 5 votes vote down vote up
def parse_args(self, args=None, namespace=None):
        """Parse the command-line arguments and call the associated handler.

        The signature is the same as `argparse.ArgumentParser.parse_args
        <https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.parse_args>`_.

        Args
        ----
        args : list
            A list of argument strings.  If ``None`` the list is taken from
            ``sys.argv``.
        namespace : argparse.Namespace
            A Namespace instance.  Defaults to a new empty Namespace.

        Returns
        -------
        The return value of the handler called with the populated Namespace as
        kwargs.

        """
        assert self.initialized, '`init` must be called before `parse_args`.'
        namespace = self.parser.parse_args(args, namespace)
        handler = self._get_handler(namespace, remove_handler=True)
        if handler:
            return handler(**vars(namespace))

    # Decorators
    # ---------- 
Example 43
Project: pytest   Author: pytest-dev   File: argparsing.py    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 44
Project: hgvm-builder   Author: BD2KGenomics   File: parallelcopy.py    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>
    """
    
    # 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 45
Project: hgvm-builder   Author: BD2KGenomics   File: importsam.py    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>
    """
    
    # 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 46
Project: hgvm-builder   Author: BD2KGenomics   File: smartSam2Fastq.py    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>
    """
    
    # 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 47
Project: input-wacom-dkms   Author: cyberang3l   File: toggle-wacom-touchring-mode.py    GNU General Public License v3.0 5 votes vote down vote up
def _configureLogging(loglevel):
    """
    Configures the default logger.

    If the log level is set to NOTSET (0), the
    logging is disabled

    # More info here: https://docs.python.org/2/howto/logging.html
    """
    numeric_log_level = getattr(logging, loglevel.upper(), None)
    try:
        if not isinstance(numeric_log_level, int):
            raise ValueError()
    except ValueError:
        error_and_exit('Invalid log level: %s\n'
        '\tLog level must be set to one of the following:\n'
        '\t   CRITICAL <- Least verbose\n'
        '\t   ERROR\n'
        '\t   WARNING\n'
        '\t   INFO\n'
        '\t   DEBUG    <- Most verbose'  % loglevel)

    defaultLogger = logging.getLogger('default')

    # If numeric_log_level == 0 (NOTSET), disable logging.
    if(not numeric_log_level):
        numeric_log_level = 1000
    defaultLogger.setLevel(numeric_log_level)

    logFormatter = logging.Formatter()

    defaultHandler = logging.StreamHandler()
    defaultHandler.setFormatter(logFormatter)

    defaultLogger.addHandler(defaultHandler)

#######################################################
###### Add command line options in this function ######
#######################################################
# Add the user defined command line arguments in this function 
Example 48
Project: input-wacom-dkms   Author: cyberang3l   File: toggle-wacom-touchring-mode.py    GNU General Public License v3.0 5 votes vote down vote up
def _command_Line_Options():
    """
    Define the accepted command line arguments in this function

    Read the documentation of argparse for more advanced command line
    argument parsing examples
    http://docs.python.org/2/library/argparse.html
    """

    parser = argparse.ArgumentParser(description=PROGRAM_NAME + " version " + VERSION)

    parser.add_argument("-v", "--version",
                        action="version", default=argparse.SUPPRESS,
                        version=VERSION,
                        help="show program's version number and exit")

    loggingGroupOpts = parser.add_argument_group('Logging Options', 'List of optional logging options')
    loggingGroupOpts.add_argument("-q", "--quiet",
                                  action="store_true",
                                  default=False,
                                  dest="isQuiet",
                                  help="Disable logging in the console. Nothing will be printed.")
    loggingGroupOpts.add_argument("-l", "--loglevel",
                                  action="store",
                                  default="INFO",
                                  dest="loglevel",
                                  metavar="LOG_LEVEL",
                                  help="LOG_LEVEL might be set to: CRITICAL, ERROR, WARNING, INFO, DEBUG. (Default: INFO)")

    opts = parser.parse_args()

    if(opts.isQuiet):
        opts.loglevel = "NOTSET"

    return opts


#---------------------------------------------------------------------- 
Example 49
Project: linear_neuron   Author: uglyboxer   File: config.py    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 50
Project: nRF5-universal-prog   Author: NordicPlayground   File: __main__.py    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 51
Project: basescript   Author: deep-compute   File: basescript.py    MIT License 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 52
Project: pyBPDL   Author: Borda   File: run_dataset_generate.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def aparse_params():
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return obj:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--path_out', type=str, required=False,
                        default=DEFAULT_PATH_APD,
                        help='path to the output dataset')
    parser.add_argument('--nb_samples', type=int, required=False,
                        default=NB_SAMPLES,
                        help='number of samples to be generated')
    parser.add_argument('--nb_patterns', type=int, required=False,
                        default=NB_ATM_PATTERNS,
                        help='number of atom. patterns in created dictionary')
    parser.add_argument('--image_size', type=int, required=False, nargs='+',
                        default=IMAGE_SIZE[DATASET_TYPE],
                        help='dimensions of generated images in axis Z, X, Y')
    parser.add_argument('--nb_workers', type=int, required=False,
                        default=NB_WORKERS,
                        help='number of processes in parallel')
    args = parser.parse_args()
    assert len(args.image_size) == 2 or len(args.image_size) == 3, \
        'unsupported image dimension of %r' % args.image_size
    args.path_out = os.path.abspath(os.path.expanduser(args.path_out))
    return args 
Example 53
Project: stitch-osm-tiles   Author: cyberang3l   File: stitch-osm-tiles.py    GNU General Public License v3.0 5 votes vote down vote up
def _configureLogging(loglevel):
    """
    Configures the default logger.

    If the log level is set to NOTSET (0), the
    logging is disabled

    # More info here: https://docs.python.org/2/howto/logging.html
    """
    numeric_log_level = getattr(logging, loglevel.upper(), None)
    try:
        if not isinstance(numeric_log_level, int):
            raise ValueError()
    except ValueError:
        error_and_exit('Invalid log level: %s\n'
                       '\tLog level must be set to one of the following:\n'
                       '\t   CRITICAL <- Least verbose\n'
                       '\t   ERROR\n'
                       '\t   WARNING\n'
                       '\t   INFO\n'
                       '\t   DEBUG    <- Most verbose'  % loglevel)

    defaultLogger = logging.getLogger('default')

    # If numeric_log_level == 0 (NOTSET), disable logging.
    if not numeric_log_level:
        numeric_log_level = 1000
    defaultLogger.setLevel(numeric_log_level)

    logFormatter = logging.Formatter()

    defaultHandler = logging.StreamHandler()
    defaultHandler.setFormatter(logFormatter)

    defaultLogger.addHandler(defaultHandler)

#######################################################
###### Add command line options in this function ######
#######################################################
# Add the user defined command line arguments in this function 
Example 54
Project: aws-encryption-sdk-cli   Author: aws   File: arg_parsing.py    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) 
Example 55
Project: django-slack   Author: oditorium   File: slack.py    MIT License 5 votes vote down vote up
def parse(s, parser, remainder):
        """runs the parser and the remainder text

        EXAMPLE
            parser = s.parser() # creates a new parser
            parser.add_argument("-c", "--channel", action="count")
                # see https://docs.python.org/3/library/argparse.html#action
            ...
            parse_obj = parse(parser, remainder) # remainder is part after subcommand
            parse_obj.error # True or False
            parse_obj.errmsg # only if .error == True
            parse_obj.remainder # all arguments not explicitly declared (as list!)

        NOTE 
        if the parser provided to the run function is used this can be simplified:
            
            def run_xxx(remainder, parser)
                parser.add_argument("-c", "--channel", action="count")
                parse_obj = parser.run()
                ...as above
                
        """
        params = remainder.split(' ')
        if params == ['']: params = []
        parser.add_argument('posn', nargs='*')
            # collects all positional arguments that have not been collected before into a list
            
        try:
            parse_obj = parser.parse_args(params)
            parse_obj.error = False
                # the results of the parsing are provides as an object; we also set .error=False
                # it is possible to convert it to a dict using vars(parse_obj)
        except SystemExit: 
            parse_obj = argparse.Namespace(error=True, errmsg=parser._error)
                # if there is an error we set .error=True, and the message goes into .errmsg
        return parse_obj


##############################################################
## POSITIONAL ARGS (decorator) 
Example 56
Project: management-api   Author: rancher   File: config.py    Apache License 2.0 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 57
Project: management-api   Author: rancher   File: config.py    Apache License 2.0 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 58
Project: pyImSegm   Author: Borda   File: run_eval_superpixels.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params(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 directory & name pattern for image',
                        default=params['path_images'])
    parser.add_argument('-segm', '--path_segms', type=str, required=False,
                        help='path to directory & name pattern for annotation',
                        default=params['path_segms'])
    parser.add_argument('-out', '--path_out', type=str, required=False,
                        help='path to the output directory',
                        default=params['path_out'])
    parser.add_argument('--img_type', type=str, required=False,
                        default=params['img_type'], choices=TYPES_LOAD_IMAGE,
                        help='type of image to be loaded')
    parser.add_argument('--slic_size', type=int, required=False,
                        default=20, help='superpixels size')
    parser.add_argument('--slic_regul', type=float, required=False,
                        default=0.25, help='superpixel regularization')
    parser.add_argument('--slico', action='store_true', required=False,
                        default=False, help='using SLICO (ASLIC)')
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes in parallel')
    params = vars(parser.parse_args())
    logging.info('ARG PARAMETERS: \n %r', params)
    for k in (k for k in params if 'path' in k):
        params[k] = tl_data.update_path(params[k])
        if k == 'path_out' and not os.path.isdir(params[k]):
            params[k] = ''
            continue
        p = os.path.dirname(params[k]) if '*' in params[k] else params[k]
        assert os.path.exists(p), 'missing: (%s) "%s"' % (k, p)
    # if the config path is set load the it otherwise use default
    return params 
Example 59
Project: pyImSegm   Author: Borda   File: run_ovary_segm_evaluation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params(paths):
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return ({str: ...}, bool, int):
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--images', type=str, required=False,
                        help='path to directory & name pattern for images',
                        default=paths['images'])
    parser.add_argument('--annots', type=str, required=False,
                        help='path to directory & name pattern for annotation',
                        default=paths['annots'])
    parser.add_argument('--segments', type=str, required=False,
                        help='path to directory & name pattern for segmentation',
                        default=paths['segments'])
    parser.add_argument('--centers', type=str, required=False,
                        help='path to directory & name pattern for centres',
                        default=paths['centers'])
    parser.add_argument('--results', type=str, required=False,
                        help='path to the result directory',
                        default=paths['results'])
    parser.add_argument('--nb_workers', type=int, required=False,
                        default=NB_WORKERS, help='number of processes in parallel')
    parser.add_argument('--visual', required=False, action='store_true',
                        default=False, help='export visualisations')
    arg_params = vars(parser.parse_args())
    export_visual = arg_params['visual']
    for k in (k for k in arg_params if k != 'nb_workers' and k != 'visual'):
        if not isinstance(arg_params[k], str) or arg_params[k].lower() == 'none':
            paths[k] = None
            continue
        paths[k] = tl_data.update_path(arg_params[k], absolute=True)
        p = paths[k] if k == 'results' else os.path.dirname(paths[k])
        assert os.path.exists(p), 'missing: %s' % p
    logging.info('ARG PARAMETERS: \n %s', (paths))
    return paths, export_visual, arg_params['nb_workers'] 
Example 60
Project: pyImSegm   Author: Borda   File: run_ellipse_annot_match.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def arg_parse_params(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 directory & name pattern for images',
                        default=params.get('path_images', None))
    parser.add_argument('-ells', '--path_ellipses', type=str, required=False,
                        help='path to directory & name pattern for ellipses',
                        default=params.get('path_ellipses', None))
    parser.add_argument('-info', '--path_infofile', type=str, required=False,
                        help='path to the global information file',
                        default=params.get('path_infofile', None))
    parser.add_argument('-out', '--path_output', type=str, required=False,
                        help='path to the output directory',
                        default=params.get('path_output', None))
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes in parallel')
    arg_params = vars(parser.parse_args())
    params.update(arg_params)
    for k in (k for k in params if 'path' in k and params[k] is not None):
        params[k] = tl_data.update_path(params[k], absolute=True)
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 61
Project: pyImSegm   Author: Borda   File: run_ovary_egg-segmentation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def segment_active_contour(img, centers):
    """ segmentation using acive contours

    :param ndarray img: input image / segmentation
    :param [[int, int]] centers: position of centres / seeds
    :return (ndarray, [[int, int]]): resulting segmentation, updated centres
    """
    logging.debug('segment: active_contour...')
    # http://scikit-image.org/docs/dev/auto_examples/edges/plot_active_contours.html
    segm = np.zeros(img.shape[:2])
    img_smooth = ndimage.filters.gaussian_filter(img, 5)
    center_circles, _, _ = create_circle_center(img.shape[:2], centers)
    for i, snake in enumerate(center_circles):
        snake = segmentation.active_contour(img_smooth, snake.astype(float),
                                            alpha=0.015, beta=10, gamma=0.001,
                                            w_line=0.0, w_edge=1.0,
                                            max_px_move=1.0,
                                            max_iterations=2500,
                                            convergence=0.2)
        seg = np.zeros(segm.shape, dtype=bool)
        x, y = np.array(snake).transpose().tolist()
        # rr, cc = draw.polygon(x, y)
        seg[map(int, x), map(int, y)] = True
        seg = morphology.binary_dilation(seg, selem=morphology.disk(3))
        bb_area = int((max(x) - min(x)) * (max(y) - min(y)))
        logging.debug('bounding box area: %d', bb_area)
        seg = morphology.remove_small_holes(seg, min_size=bb_area)
        segm[seg] = i + 1
    return segm, centers, None 
Example 62
Project: python-3-scicomp-intro   Author: Technologicat   File: mro.py    Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def main():
    # Let's make a simple command-line interface for the program.
    #
    # Tutorial and API reference:
    #   https://docs.python.org/3/howto/argparse.html
    #   https://docs.python.org/3/library/argparse.html
    #
    desc = ('Determine method resolution order (MRO) in classes defined in a given Python source file.')
    parser = argparse.ArgumentParser(description=desc)

    # named command-line options (help message -h, --help always implicitly provided)
    parser.add_argument('-v', '--version', action='version', version=('%(prog)s ' + __version__) )
    parser.add_argument('-l', '--log', dest='logname', help='write log messages to LOG', metavar='LOG', default=None)

    # positional command-line options
    parser.add_argument('filename', help='Filename of a Python source file (.py) to analyze.')

    # Parse the command line. This will automatically terminate the program if:
    #  - the user asked for -h or -v
    #  - no filename was specified
    #
    args = parser.parse_args()

    # Messages will be printed to sys.stderr (default), and optionally
    # also into a log file.
    #
    # Tutorial and API reference:
    #   https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
    #   https://docs.python.org/3/library/logging.html
    #
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)  # DEBUG, INFO, WARN, ERROR
    logger.addHandler(logging.StreamHandler())
    if args.logname is not None:
        handler = logging.FileHandler(args.logname)
        logger.addHandler(handler)

    # Start the analyzer.
    #
    m = MROVisitor(args.filename, logger)
    m.run() 
Example 63
Project: abseil-py   Author: abseil   File: argparse_flags.py    Apache License 2.0 5 votes vote down vote up
def parse_known_args(self, args=None, namespace=None):
    if args is None:
      args = sys.argv[1:]
    if self._inherited_absl_flags:
      # Handle --flagfile.
      # Explicitly specify force_gnu=True, since argparse behaves like
      # gnu_getopt: flags can be specified after positional arguments.
      args = self._inherited_absl_flags.read_flags_from_files(
          args, force_gnu=True)

    undefok_missing = object()
    undefok = getattr(namespace, 'undefok', undefok_missing)

    namespace, args = super(ArgumentParser, self).parse_known_args(
        args, namespace)

    # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where
    # sub-parsers don't preserve existing namespace attributes.
    # Restore the undefok attribute if a sub-parser dropped it.
    if undefok is not undefok_missing:
      namespace.undefok = undefok

    if self._inherited_absl_flags:
      # Handle --undefok. At this point, `args` only contains unknown flags,
      # so it won't strip defined flags that are also specified with --undefok.
      # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where
      # sub-parsers don't preserve existing namespace attributes. The undefok
      # attribute might not exist because a subparser dropped it.
      if hasattr(namespace, 'undefok'):
        args = _strip_undefok_args(namespace.undefok, args)
        # absl flags are not exposed in the Namespace object. See Namespace:
        # https://docs.python.org/3/library/argparse.html#argparse.Namespace.
        del namespace.undefok
      self._inherited_absl_flags.mark_as_parsed()
      try:
        self._inherited_absl_flags._assert_all_validators()  # pylint: disable=protected-access
      except flags.IllegalFlagValueError as e:
        self.error(str(e))

    return namespace, args 
Example 64
Project: abseil-py   Author: abseil   File: argparse_flags.py    Apache License 2.0 5 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."""
    self._flag_instance.parse(values)
    self._flag_instance.using_default_value = False 
Example 65
Project: abseil-py   Author: abseil   File: argparse_flags.py    Apache License 2.0 5 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."""
    if not isinstance(values, list) or values:
      raise ValueError('values must be an empty list.')
    if option_string.startswith('--'):
      option = option_string[2:]
    else:
      option = option_string[1:]
    if option in self._flag_names:
      self._flag_instance.parse('true')
    else:
      if not option.startswith('no') or option[2:] not in self._flag_names:
        raise ValueError('invalid option_string: ' + option_string)
      self._flag_instance.parse('false')
    self._flag_instance.using_default_value = False 
Example 66
Project: initsearchtool   Author: intel   File: isearch.py    Apache License 2.0 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 67
Project: checkmk-collector   Author: finalduty   File: datasource.py    MIT License 5 votes vote down vote up
def main():
    ## Parse CommandLine arguments
    ## https://docs.python.org/2/howto/argparse.html

    parser = argparse.ArgumentParser()
    parser.add_argument("--host", "--hostname", required=True, help="Hostname to get status data for")
    parser.add_argument("--api", "--api_base_url", required=False, help="API Base URL", default='http://127.0.0.1:8080/collector/api/v0.1/hosts')

    args = parser.parse_args()
    hostname = args.host
    api_base_url = args.api

    get_status(hostname,api_base_url) 
Example 68
Project: InfiniBand-Graphviz-ualization   Author: cyberang3l   File: infiniband-graphviz.py    GNU General Public License v3.0 5 votes vote down vote up
def _configureLogging(loglevel):
    """
    Configures the default logger.

    If the log level is set to NOTSET (0), the
    logging is disabled

    # More info here: https://docs.python.org/2/howto/logging.html
    """
    numeric_log_level = getattr(logging, loglevel.upper(), None)
    try:
        if not isinstance(numeric_log_level, int):
            raise ValueError()
    except ValueError:
        error_and_exit('Invalid log level: %s\n'
        '\tLog level must be set to one of the following:\n'
        '\t   CRITICAL <- Least verbose\n'
        '\t   ERROR\n'
        '\t   WARNING\n'
        '\t   INFO\n'
        '\t   DEBUG    <- Most verbose'  % loglevel)

    defaultLogger = logging.getLogger('default')

    # If numeric_log_level == 0 (NOTSET), disable logging.
    if(not numeric_log_level):
        numeric_log_level = 1000
    defaultLogger.setLevel(numeric_log_level)

    logFormatter = logging.Formatter()

    defaultHandler = logging.StreamHandler()
    defaultHandler.setFormatter(logFormatter)

    defaultLogger.addHandler(defaultHandler)

#######################################################
###### Add command line options in this function ######
#######################################################
# Add the user defined command line arguments in this function 
Example 69
Project: Namsor-API-Wrapper-Python   Author: JosephPallipadan   File: argparsing.py    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 70
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: argparse_flags.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_known_args(self, args=None, namespace=None):
    if args is None:
      args = sys.argv[1:]
    if self._inherited_absl_flags:
      # Handle --flagfile.
      # Explicitly specify force_gnu=True, since argparse behaves like
      # gnu_getopt: flags can be specified after positional arguments.
      args = self._inherited_absl_flags.read_flags_from_files(
          args, force_gnu=True)

    undefok_missing = object()
    undefok = getattr(namespace, 'undefok', undefok_missing)

    namespace, args = super(ArgumentParser, self).parse_known_args(
        args, namespace)

    # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where
    # sub-parsers don't preserve existing namespace attributes.
    # Restore the undefok attribute if a sub-parser dropped it.
    if undefok is not undefok_missing:
      namespace.undefok = undefok

    if self._inherited_absl_flags:
      # Handle --undefok. At this point, `args` only contains unknown flags,
      # so it won't strip defined flags that are also specified with --undefok.
      # For Python <= 2.7.8: https://bugs.python.org/issue9351, a bug where
      # sub-parsers don't preserve existing namespace attributes. The undefok
      # attribute might not exist because a subparser dropped it.
      if hasattr(namespace, 'undefok'):
        args = _strip_undefok_args(namespace.undefok, args)
        # absl flags are not exposed in the Namespace object. See Namespace:
        # https://docs.python.org/3/library/argparse.html#argparse.Namespace.
        del namespace.undefok
      self._inherited_absl_flags.mark_as_parsed()
      try:
        self._inherited_absl_flags._assert_all_validators()  # pylint: disable=protected-access
      except flags.IllegalFlagValueError as e:
        self.error(str(e))

    return namespace, args 
Example 71
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: argparse_flags.py    GNU General Public License v3.0 5 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."""
    self._flag_instance.parse(values)
    self._flag_instance.using_default_value = False 
Example 72
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: argparse_flags.py    GNU General Public License v3.0 5 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."""
    if not isinstance(values, list) or values:
      raise ValueError('values must be an empty list.')
    if option_string.startswith('--'):
      option = option_string[2:]
    else:
      option = option_string[1:]
    if option in self._flag_names:
      self._flag_instance.parse('true')
    else:
      if not option.startswith('no') or option[2:] not in self._flag_names:
        raise ValueError('invalid option_string: ' + option_string)
      self._flag_instance.parse('false')
    self._flag_instance.using_default_value = False 
Example 73
Project: hgvm-builder   Author: BD2KGenomics   File: chromMatcher.py    Apache License 2.0 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) 
Example 74
Project: stitch-osm-tiles   Author: cyberang3l   File: stitch-osm-tiles.py    GNU General Public License v3.0 4 votes vote down vote up
def DrawableMapLabels(map_width, map_height, canvas_margin, fontsize=80, x_grid_by=256, y_grid_by=256):
    """
    Draw the labels on the sides of the canvas

    This function could be merged with the DrawableMapGrid function
    but we keep it separate for fine tuning. The grid for example may need to be
    semitransparent, but the labels should not
    """
    labels = pgmagick.DrawableList()

    fontname = 'FreeSans'
    labels.append(pgmagick.DrawableFont(fontname, pgmagick.StyleType.NormalStyle, 600, pgmagick.StretchType.NormalStretch))
    labels.append(pgmagick.DrawablePointSize(fontsize))
    labels.append(pgmagick.DrawableGravity(pgmagick.GravityType.NorthWestGravity))

    # Use an image object, in order to make use of the fontmetrics capability.
    text = pgmagick.Image()
    text.fontPointsize(fontsize)
    text.font(fontname)
    fontmetric = pgmagick.TypeMetric()

    x_grid_by = x_grid_by + (map_width % x_grid_by / float(int(map_width / x_grid_by)))
    y_grid_by = y_grid_by + (map_height % y_grid_by / float(int(map_height / y_grid_by)))

    ascii_chr = [65] # ASCII 65 = A
    for x in xfrange(canvas_margin, map_width + canvas_margin, x_grid_by):
        x = round(x)
        lab = ''.join(chr(i) for i in ascii_chr)
        pgmagick.Image.fontTypeMetrics(text, lab, fontmetric)
        labels.append(pgmagick.DrawableText(x + int(x_grid_by / 2) - int(fontmetric.textWidth() / 2), canvas_margin - 30, lab))
        labels.append(pgmagick.DrawableText(x + int(x_grid_by / 2) - int(fontmetric.textWidth() / 2),
                                            map_height + canvas_margin + 30 + (fontmetric.ascent() + fontmetric.descent()), lab))
        # If we reached Z, start counting from AA, AB, AC etc...
        # This if so far it will only work until ZZ which I think is more than enough.
        if ascii_chr[len(ascii_chr) - 1] < 90: # ASCII 90 = Z
            ascii_chr[len(ascii_chr) - 1] += 1
        else:
            if len(ascii_chr) == 1:
                ascii_chr[0] = 65
                ascii_chr.append(65)
            else:
                ascii_chr[0] += 1
                ascii_chr[1] = 65

    lab = 1
    for y in xfrange(canvas_margin, map_height + canvas_margin, y_grid_by):
        y = round(y)
        pgmagick.Image.fontTypeMetrics(text, str(lab), fontmetric)
        # http://www.graphicsmagick.org/Magick++/TypeMetric.html
        labels.append(pgmagick.DrawableText(canvas_margin - fontmetric.textWidth() - 30,
                                            y + int(y_grid_by / 2) + int((fontmetric.ascent() + fontmetric.descent()) / 2), str(lab)))
        labels.append(pgmagick.DrawableText(map_width + canvas_margin + 30,
                                            y + int(y_grid_by / 2) + int((fontmetric.ascent() + fontmetric.descent()) / 2), str(lab)))
        lab += 1

    return labels

#---------------------------------------------------------------------- 
Example 75
Project: snippets   Author: jeremiedecock   File: test.py    MIT License 4 votes vote down vote up
def main():
    """Main function"""

    parser = argparse.ArgumentParser(description='An argparse snippet.')

    # add_argument (see http://docs.python.org/2/library/argparse.html#the-add-argument-method)
    # - name or flags: Either a name or a list of option strings, e.g. foo or -f, --foo.
    # - action: The basic type of action to be taken when this argument is encountered at the command line
    #     - 'store': This just stores the argument’s value. This is the default action.
    #     - 'store_const': This stores the value specified by the const keyword argument.
    #     - 'store_true': This is a special cases of 'store_const' using for storing the value True.
    #     - 'store_false': This is a special cases of 'store_const' using for storing the value False.
    #     - 'append': This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.
    #     - 'append_const': This stores a list, and appends the value specified by the const keyword argument to the list.
    #     - 'count': This counts the number of times a keyword argument occurs.
    #     - 'help': This prints a complete help message for all the options in the current parser and then exits.
    #     - 'version': This expects a version= keyword argument in the add_argument() call, and prints version information and exits.
    # - nargs: The number of command-line arguments that should be consumed.
    # - const: A constant value required by some action and nargs selections.
    # - default: The value produced if the argument is absent from the command line.
    # - type: The type to which the command-line argument should be converted.
    # - choices: A container of the allowable values for the argument.
    # - required: Whether or not the command-line option may be omitted (optionals only).
    # - help: A brief description of what the argument does.
    # - metavar: A name for the argument in usage messages.
    # - dest: The name of the attribute to be added to the object returned by parse_args().
    parser.add_argument("--stropt", "-s", required=True, metavar="STRING",
            help="an example of str option")

    parser.add_argument("--intopt", "-i", type=int, default=3, metavar="INTEGER",
            help="an example of int option (default: 3)")

    parser.add_argument("--floatopt", "-f", type=float, default=3.14, metavar="FLOAT",
            help="an example of float option (default: 3.14)")

    parser.add_argument("--boolopt", "-b", action="store_true",
            help="an example of flag (boolean option)")

    parser.add_argument("fileargs", nargs="*", type=file, metavar="FILE",
            help="an example of file arguments")

    args = parser.parse_args()

    print "args.stropt:", args.stropt
    print "args.intopt:", args.intopt
    print "args.floatopt:", args.floatopt
    print "args.boolopt:", args.boolopt
    print "args.fileargs:", args.fileargs 
Example 76
Project: pyImSegm   Author: Borda   File: run_compute_stat_annot_segm.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def aparse_params(dict_paths):
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return ({str: str}, obj):
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--path_annot', type=str, required=True,
                        help='path to directory with annotations & name pattern',
                        default=dict_paths['annot'])
    parser.add_argument('-s', '--path_segm', type=str, required=True,
                        help='path to directory & name pattern for segmentation',
                        default=dict_paths['segm'])
    parser.add_argument('-i', '--path_image', type=str, required=False,
                        help='path to directory & name pattern for images',
                        default=dict_paths['image'])
    parser.add_argument('-o', '--path_output', type=str, required=False,
                        help='path to the output directory',
                        default=dict_paths['output'])
    parser.add_argument('--drop_labels', type=int, required=False, nargs='*',
                        help='list of skipped labels from statistic')
    parser.add_argument('--nb_workers', type=int, required=False,
                        help='number of processes in parallel',
                        default=NB_WORKERS)
    parser.add_argument('--overlap', type=float, required=False,
                        help='alpha for segmentation', default=0.2)
    parser.add_argument('--relabel', required=False, action='store_true',
                        help='relabel to find label relations', default=False)
    parser.add_argument('--visual', required=False, action='store_true',
                        help='export visualisations', default=False)
    args = vars(parser.parse_args())
    logging.info('ARG PARAMETERS: \n %r', args)
    if not isinstance(args['path_image'], str) or args['path_image'].lower() == 'none':
        args['path_image'] = None

    _fn_path = lambda k: os.path.join(tl_data.update_path(os.path.dirname(args[k])),
                                      os.path.basename(args[k]))
    dict_paths = {k.split('_')[-1]: _fn_path(k)
                  for k in args if k.startswith('path_') and args[k] is not None}
    for k in dict_paths:
        assert os.path.isdir(os.path.dirname(dict_paths[k])), \
            'missing: (%s) "%s"' % (k, os.path.dirname(dict_paths[k]))
    if not args['drop_labels']:
        args['drop_labels'] = []
    return dict_paths, args 
Example 77
Project: pyImSegm   Author: Borda   File: run_segm_slic_model_graphcut.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def arg_parse_params(params):
    """ argument parser from cmd

    SEE: https://docs.python.org/3/library/argparse.html
    :return dict:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--path_train_list', type=str, required=False,
                        help='path to the list of image',
                        default=params['path_train_list'])
    parser.add_argument('-i', '--path_predict_imgs', type=str, required=False,
                        help='path to folder & name pattern with new image',
                        default=params['path_predict_imgs'])
    parser.add_argument('-o', '--path_out', type=str, required=False,
                        help='path to the output directory',
                        default=params['path_out'])
    parser.add_argument('-n', '--name', type=str, required=False,
                        help='name of the experiment', default=params['name'])
    parser.add_argument('-cfg', '--path_config', type=str, required=False,
                        help='path to the segmentation config', default='')
    parser.add_argument('--img_type', type=str, required=False,
                        default=params['img_type'], choices=TYPES_LOAD_IMAGE,
                        help='type of image to be loaded')
    parser.add_argument('--nb_classes', type=int, required=False,
                        help='number of classes for segmentation',
                        default=params.get('nb_classes', 2))
    parser.add_argument('--nb_workers', type=int, required=False,
                        help='number of processes in parallel',
                        default=NB_WORKERS)
    parser.add_argument('--visual', required=False, action='store_true',
                        help='export debug visualisations', default=False)
    parser.add_argument('--unique', required=False, action='store_true',
                        help='each experiment has uniques stamp',
                        default=EACH_UNIQUE_EXPERIMENT)
    args = vars(parser.parse_args())
    logging.info('ARG PARAMETERS: \n %r', args)
    for k in (k for k in args if 'path' in k):
        if args[k] == '' or args[k] == 'none':
            continue
        args[k] = tl_data.update_path(args[k])
        p = os.path.dirname(args[k]) if k == 'path_predict_imgs' else args[k]
        assert os.path.exists(p), 'missing: (%s) "%s"' % (k, p)
    # args['visual'] = bool(args['visual'])
    # if the config path is set load the it otherwise use default
    if os.path.isfile(args.get('path_config', '')):
        config = tl_expt.load_config_yaml(args['path_config'])
        params.update(config)
    params.update(args)
    return params 
Example 78
Project: pyImSegm   Author: Borda   File: run_center_candidate_training.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def arg_parse_params(params):
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return dict:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-list', '--path_list', type=str, required=False,
                        help='path to the list of input files',
                        default=params['path_list'])
    parser.add_argument('-imgs', '--path_images', type=str, required=False,
                        help='path to directory & name pattern for images',
                        default=params['path_images'])
    parser.add_argument('-segs', '--path_segms', type=str, required=False,
                        help='path to directory & name pattern for segmentation',
                        default=params['path_segms'])
    parser.add_argument('-centers', '--path_centers', type=str, required=False,
                        help='path to directory & name pattern for centres',
                        default=params['path_centers'])
    parser.add_argument('-info', '--path_infofile', type=str, required=False,
                        help='path to the global information file',
                        default=params['path_infofile'])
    parser.add_argument('-out', '--path_output', type=str, required=False,
                        help='path to the output directory',
                        default=params['path_output'])
    parser.add_argument('-n', '--name', type=str, required=False,
                        help='name of the experiment', default='ovary')
    parser.add_argument('-cfg', '--path_config', type=str, required=False,
                        help='path to the configuration', default=None)
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes in parallel')
    params.update(vars(parser.parse_args()))
    paths = {}
    for k in (k for k in params if 'path' in k):
        if not isinstance(params[k], str) or params[k].lower() == 'none':
            paths[k] = ''
            continue
        if k in ['path_images', 'path_segms', 'path_centers', 'path_expt']:
            p_dir = tl_data.update_path(os.path.dirname(params[k]))
            paths[k] = os.path.join(p_dir, os.path.basename(params[k]))
        else:
            paths[k] = tl_data.update_path(params[k], absolute=True)
            p_dir = paths[k]
        assert os.path.exists(p_dir), 'missing (%s) %s' % (k, p_dir)
    # load saved configuration
    if params['path_config'] is not None:
        ext = os.path.splitext(params['path_config'])[-1]
        assert (ext == '.yaml' or ext == '.yml'), \
            'wrong extension for %s' % params['path_config']
        data = tl_expt.load_config_yaml(params['path_config'])
        params.update(data)
    params.update(paths)
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 79
Project: pyImSegm   Author: Borda   File: run_ovary_egg-segmentation.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def arg_parse_params(params):
    """
    SEE: https://docs.python.org/3/library/argparse.html
    :return {str: str}:
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-list', '--path_list', type=str, required=False,
                        help='path to the list of image',
                        default=params['path_list'])
    parser.add_argument('-out', '--path_out', type=str, required=False,
                        help='path to the output directory',
                        default=params['path_out'])
    parser.add_argument('-n', '--name', type=str, required=False,
                        help='name of the experiment', default='ovary')
    parser.add_argument('-cfg', '--path_config', type=str, required=False,
                        help='path to the configuration', default=None)
    parser.add_argument('--nb_workers', type=int, required=False, default=NB_WORKERS,
                        help='number of processes in parallel')
    parser.add_argument('-m', '--methods', type=str, required=False, nargs='+',
                        help='list of segment. methods', default=None)
    arg_params = vars(parser.parse_args())
    params.update(arg_params)
    if not isinstance(arg_params['path_config'], str) \
            or arg_params['path_config'].lower() == 'none':
        params['path_config'] = ''
    else:
        params['path_config'] = tl_data.update_path(params['path_config'])
        assert os.path.isfile(params['path_config']), \
            'missing file: %s' % params['path_config']
        ext = os.path.splitext(params['path_config'])[-1]
        assert (ext == '.yaml' or ext == '.yml'), \
            '"%s" should be YAML file' % os.path.basename(params['path_config'])
        data = tl_expt.load_config_yaml(params['path_config'])
        params.update(data)
        params.update(arg_params)
    for k in (k for k in arg_params if 'path' in k):
        if not arg_params[k]:
            continue
        params[k] = tl_data.update_path(arg_params[k], absolute=True)
        assert os.path.exists(params[k]), 'missing: %s' % params[k]
    # load saved configuration
    logging.info('ARG PARAMETERS: \n %r', params)
    return params 
Example 80
Project: mkdocs-versioning   Author: zayd62   File: __main__.py    MIT License 4 votes vote down vote up
def parse_cmd(cmd):

    # help definitions
    config_help = 'Provide a specific MkDocs config'
    commit_message_help = ('A commit message to use when committing to the Github Pages remote branch. Commit {sha} '
                           'and MkDocs {version} are available as expansions')
    remote_branch_help = ('The remote branch to commit to for Github Pages. This overrides the value specified in '
                          'config')
    remote_name_help = 'The remote name to commit to for Github Pages. This overrides the value specified in config'
    force_help = 'Force the push to the repository.'
    ignore_version_help = 'Ignore check that build is not being deployed with an older version of MkDocs.'
    sync_description = 'Used to sync GitHub pages branch to built docs directory. Run if local docs are not the same ' \
                       'as the ones available on Github pages. e.g after cloning the repository '

    #####################################################################
    #            Code for parsing command line arguments                #
    #####################################################################
    # https://docs.python.org/3.7/howto/argparse.html
    # https://docs.python.org/3/library/argparse.html

    # create the argument parser
    parser = argparse.ArgumentParser(
        description='A tool that allows the versioning of documentation built using mkdocs')
    # mutually exclusive means that only one option can be supplied. supplying both will result in an error
    group = parser.add_mutually_exclusive_group()
    # "store_true" means that if the argument is provided, the value of the argument is true
    group.add_argument('-v', '--verbose', action='store_true', help='Give more output')
    group.add_argument('-q', '--quiet', action='store_true', help='Give no output')
    # create sub parser
    subparser = parser.add_subparsers(title='Sub-commands', description='List of available sub-commands',
                                      help='List of sub-commands', dest='subparser_name')

    # add command deploy
    parser_deploy = subparser.add_parser(
        'deploy', description='Command used to deploy documentation to GitHub Pages',
        help='Deploy documentation to Github Pages')
    parser_deploy.set_defaults(func=utils.deploy)  # add default function for deploy command
    # add arguments for deploy command

    parser_deploy.add_argument('-f', '--config-file', help=config_help, metavar='FILE',
                               type=argparse.FileType(mode='rb'))
    parser_deploy.add_argument('-m', '--message', help=commit_message_help)
    parser_deploy.add_argument('-b', '--remote-branch', help=remote_branch_help)
    parser_deploy.add_argument('-r', '--remote-name', help=remote_name_help)
    parser_deploy.add_argument('--force', action='store_true', help=force_help)
    parser_deploy.add_argument('--ignore-version', action='store_true', help=ignore_version_help)

    # add command sync
    parser_sync = subparser.add_parser('sync', description=sync_description, help='Sync GitHub Pages to local docs')
    parser_sync.set_defaults(func=utils.sync)
    parser_sync.add_argument('-f', '--config-file', help=config_help, metavar='FILE', type=argparse.FileType(mode='rb'))

    # check if no arguments were passed. if true, print help
    if len(cmd) == 0:
        parser.print_help()
        sys.exit(1)

    # writing the arguments to a variable to be accessed
    args = parser.parse_args(cmd)
    return args