Python configargparse.ArgParser() Examples

The following are 7 code examples of configargparse.ArgParser(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module configargparse , or try the search function .
Example #1
Source File: test_configargparse.py    From ConfigArgParse with MIT License 6 votes vote down vote up
def initParser(self, *args, **kwargs):
        p = configargparse.ArgParser(*args, **kwargs)
        self.parser = replace_error_method(p)
        self.add_arg = self.parser.add_argument
        self.parse = self.parser.parse_args
        self.parse_known = self.parser.parse_known_args
        self.format_values = self.parser.format_values
        self.format_help = self.parser.format_help

        if not hasattr(self, "assertRegex"):
            self.assertRegex = self.assertRegexpMatches
        if not hasattr(self, "assertRaisesRegex"):
            self.assertRaisesRegex = self.assertRaisesRegexp

        return self.parser 
Example #2
Source File: config.py    From HyperGCN with Apache License 2.0 5 votes vote down vote up
def parse():
	"""
	adds and parses arguments / hyperparameters
	"""
	default = os.path.join(current(), data + ".yml")
	p = configargparse.ArgParser(config_file_parser_class = YAMLConfigFileParser, default_config_files=[default])
	p.add('-c', '--my-config', is_config_file=True, help='config file path')
	p.add('--data', type=str, default=data, help='data name (coauthorship/cocitation)')
	p.add('--dataset', type=str, default=dataset, help='dataset name (e.g.: cora/dblp/acm for coauthorship, cora/citeseer/pubmed for cocitation)')
	p.add('--mediators', type=bool, default=mediators, help='True for Laplacian with mediators, False for Laplacian without mediators')
	p.add('--fast', type=bool, default=fast, help='faster version of HyperGCN (True)')
	p.add('--split', type=int, default=split, help='train-test split used for the dataset')
	p.add('--depth', type=int, default=depth, help='number of hidden layers')
	p.add('--dropout', type=float, default=dropout, help='dropout probability for GCN hidden layer')
	p.add('--rate', type=float, default=rate, help='learning rate')
	p.add('--decay', type=float, default=decay, help='weight decay')
	p.add('--epochs', type=int, default=epochs, help='number of epochs to train')
	p.add('--gpu', type=int, default=gpu, help='gpu number to use')
	p.add('--cuda', type=bool, default=cuda, help='cuda for gpu')
	p.add('--seed', type=int, default=seed, help='seed for randomness')
	p.add('-f') # for jupyter default
	return p.parse_args() 
Example #3
Source File: syntester.py    From dynatrace-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create_argparser(self):
        """ Create argument parser.

        For internal use only.
        """

        parser = ArgParser(
            description="Dynatrace third-party test utility.",
            default_config_files=['./config.ini'],
            add_config_file_help=False
        )

        self._create_subparsers(parser)
        argcomplete.autocomplete(parser)
        return parser 
Example #4
Source File: opts.py    From Pytorch-Human-Pose-Estimation with MIT License 5 votes vote down vote up
def __init__(self):
		super(opts, self).__init__()
		self.parser = configargparse.ArgParser(default_config_files=[]) 
Example #5
Source File: netconan.py    From netconan with Apache License 2.0 5 votes vote down vote up
def _parse_args(argv):
    """Parse arguments from the given list."""
    parser = configargparse.ArgParser(
        # Replace the default config file help with custom message
        # To fix some syntax issues
        add_config_file_help=False,
        description="""
        Args that can start with '--' can also be set in a config file (specified
        via -c). If an arg is specified in more than one place, then command line
        values override config file values which override defaults. Config file
        syntax allows: key=value, flag=true, stuff=[a,b,c] (for more details, see
        here https://goo.gl/R74nmi).
        """
    )

    parser.add_argument('-a', '--anonymize-ips', action='store_true', default=False,
                        help='Anonymize IP addresses')
    parser.add_argument('-c', '--config', is_config_file=True,
                        help='Netconan configuration file with defaults for these CLI parameters')
    parser.add_argument('-d', '--dump-ip-map', default=None,
                        help='Dump IP address anonymization map to specified file')
    parser.add_argument('-i', '--input', required=True,
                        help='Input file or directory containing files to anonymize')
    parser.add_argument('-l', '--log-level', default='INFO',
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                        help='Determines what level of logs to display')
    parser.add_argument('-n', '--as-numbers', default=None,
                        help='List of comma separated AS numbers to anonymize')
    parser.add_argument('-o', '--output', required=True,
                        help='Output file or directory where anonymized files are placed')
    parser.add_argument('-p', '--anonymize-passwords', action='store_true', default=False,
                        help='Anonymize password and snmp community lines')
    parser.add_argument('-r', '--reserved-words', default=None,
                        help='List of comma separated words that should not be anonymized')
    parser.add_argument('-s', '--salt', default=None,
                        help='Salt for IP and sensitive keyword anonymization')
    parser.add_argument('-u', '--undo', action='store_true', default=False,
                        help='Undo reversible anonymization (must specify salt)')
    parser.add_argument('-w', '--sensitive-words', default=None,
                        help='List of comma separated keywords to anonymize')
    parser.add_argument('--preserve-prefixes',
                        default=','.join(IpAnonymizer.DEFAULT_PRESERVED_PREFIXES),
                        help='List of comma separated IP prefixes to preserve. Specified prefixes are preserved, but the host bits within those prefixes are still anonymized. To preserve prefixes and host bits in specified blocks, use --preserve-addresses instead')
    parser.add_argument('--preserve-addresses', default=None,
                        help='List of comma separated IP addresses or networks to preserve. Prefixes and host bits within those networks are preserved.  To preserve just prefixes and anonymize host bits, use --preserve-prefixes')
    parser.add_argument('--preserve-private-addresses',
                        action='store_true', default=False,
                        help='Preserve private-use IP addresses. Prefixes and host bits within the private-use IP networks are preserved. To preserve specific addresses or networks, use --preserve-addresses instead. To preserve just prefixes and anonymize host bits, use --preserve-prefixes')
    return parser.parse_args(argv) 
Example #6
Source File: __init__.py    From trezor-agent with GNU Lesser General Public License v3.0 4 votes vote down vote up
def create_agent_parser(device_type):
    """Create an ArgumentParser for this tool."""
    epilog = ('See https://github.com/romanz/trezor-agent/blob/master/'
              'doc/README-SSH.md for usage examples.')
    p = configargparse.ArgParser(default_config_files=['~/.ssh/agent.config'],
                                 epilog=epilog)
    p.add_argument('-v', '--verbose', default=0, action='count')

    agent_package = device_type.package_name()
    resources_map = {r.key: r for r in pkg_resources.require(agent_package)}
    resources = [resources_map[agent_package], resources_map['libagent']]
    versions = '\n'.join('{}={}'.format(r.key, r.version) for r in resources)
    p.add_argument('--version', help='print the version info',
                   action='version', version=versions)

    curve_names = ', '.join(sorted(formats.SUPPORTED_CURVES))
    p.add_argument('-e', '--ecdsa-curve-name', metavar='CURVE',
                   default=formats.CURVE_NIST256,
                   help='specify ECDSA curve name: ' + curve_names)
    p.add_argument('--timeout',
                   default=UNIX_SOCKET_TIMEOUT, type=float,
                   help='timeout for accepting SSH client connections')
    p.add_argument('--debug', default=False, action='store_true',
                   help='log SSH protocol messages for debugging.')
    p.add_argument('--log-file', type=str,
                   help='Path to the log file (to be written by the agent).')
    p.add_argument('--sock-path', type=str,
                   help='Path to the UNIX domain socket of the agent.')

    p.add_argument('--pin-entry-binary', type=str, default='pinentry',
                   help='Path to PIN entry UI helper.')
    p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
                   help='Path to passphrase entry UI helper.')
    p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
                   help='Expire passphrase from cache after this duration.')

    g = p.add_mutually_exclusive_group()
    g.add_argument('-d', '--daemonize', default=False, action='store_true',
                   help='Daemonize the agent and print its UNIX socket path')
    g.add_argument('-f', '--foreground', default=False, action='store_true',
                   help='Run agent in foreground with specified UNIX socket path')
    g.add_argument('-s', '--shell', default=False, action='store_true',
                   help=('run ${SHELL} as subprocess under SSH agent, allowing '
                         'regular SSH-based tools to be used in the shell'))
    g.add_argument('-c', '--connect', default=False, action='store_true',
                   help='connect to specified host via SSH')
    g.add_argument('--mosh', default=False, action='store_true',
                   help='connect to specified host via using Mosh')

    p.add_argument('identity', type=_to_unicode, default=None,
                   help='proto://[user@]host[:port][/path]')
    p.add_argument('command', type=str, nargs='*', metavar='ARGUMENT',
                   help='command to run under the SSH agent')
    return p 
Example #7
Source File: cli.py    From scyllabackup with MIT License 4 votes vote down vote up
def common_parser():
    parser = configargparse.ArgParser(add_help=False)
    parser.add('-c', '--conf-file', is_config_file=True,
               help='Config file for scyllabackup')

    parser.add('-l', '--log-level', default='WARNING',
               choices=['DEBUG', 'INFO', 'WARNING',
                        'ERROR', 'CRITICAL'],
               help='Log level for scyllabackup')
    parser.add('--path', required=True, help='Path of scylla data directory')
    parser.add('--db', required=True,
               help='Path of scyllabackup db file. The backup metadata is '
               'stored in this file.')
    parser.add('--provider', required=True, choices=['s3', 'wabs'],
               help='Cloud provider used for storage. It should be one of `s3` '
               'or `wabs`')
    parser.add('--nodetool-path', default='/usr/bin/nodetool',
               help='Path of nodetool utility on filesystem.')
    parser.add('--cqlsh-path', default='/usr/bin/cqlsh',
               help='Path of cqlsh utility on filesystem')
    parser.add('--cqlsh-host', default='127.0.0.1',
               help='Host to use for connecting cqlsh service')
    parser.add('--cqlsh-port', default='9042',
               help='Port to use for connecting cqlsh service')

    s3 = parser.add_argument_group("Required arguments if using "
                                   "'s3' provider")
    s3.add('--s3-bucket-name', metavar='BUCKET_NAME',
           help='Mandatory if provider is s3')
    s3.add('--s3-aws-key', metavar='AWS_KEY',
           help='Mandatory if provider is s3')
    s3.add('--s3-aws-secret', metavar='AWS_SECRET',
           help='Mandatory if provider is s3')
    wabs = parser.add_argument_group("Required arguments if using "
                                     "'wabs' provider")
    wabs.add('--wabs-container-name', help='Mandatory if provider is wabs')
    wabs.add('--wabs-account-name', help='Mandatory if provider is wabs')
    wabs.add('--wabs-sas-token', help='Mandatory if provider is wabs')

    parser.add('--prefix', required=True,
               help='Mandatory prefix to store backups in cloud storage')

    parser.add('--lock', default='/var/run/lock/scyllabackup.lock',
               help='Lock file for scyllabackup.')

    parser.add('--lock-timeout', type=int, default=10,
               help='Timeout for taking lock.')

    parser.add('--max-workers', type=int, default=4,
               help='Sets max workers for parallelizing storage api calls')

    return parser