本文整理匯總了Python中argparse.html方法的典型用法代碼示例。如果您正苦於以下問題:Python argparse.html方法的具體用法?Python argparse.html怎麽用?Python argparse.html使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類argparse
的用法示例。
在下文中一共展示了argparse.html方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: parse_args
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例2: parse_args
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例3: error
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
def error(self, message):
"""Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the following argparse python documentation for detailed method
information:
http://docs.python.org/2/library/argparse.html#exiting-methods
Args:
message: original error message that will be printed to stderr
"""
# subcommands_quoted is the same as subcommands, except each value is
# surrounded with double quotes. This is done to match the standard
# output of the ArgumentParser, while hiding commands we don't want users
# to use, as they are no longer documented and only here for legacy use.
subcommands_quoted = ', '.join(
[repr(command) for command in _VISIBLE_COMMANDS])
subcommands = ', '.join(_VISIBLE_COMMANDS)
message = re.sub(
r'(argument {%s}: invalid choice: .*) \(choose from (.*)\)$'
% subcommands, r'\1 (choose from %s)' % subcommands_quoted, message)
super(_EndpointsParser, self).error(message)
示例4: parse_args
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例5: arg_parse_params
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例6: parse_arg_params
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例7: _add_commands
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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.
示例8: arg_parse_params
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例9: arg_parse_params
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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
示例10: _get_option_tuples
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
def _get_option_tuples(self, option_string):
"""
This method is overridden explicitly to disable argparse prefix matching. Prefix matching is an undesired
default behavior as it creates the potential for unintended breaking changes just by adding a new command-line
argument.
For example, if a user uses the argument "--master" to specify a value for "--master-url", and later we add a
new argument named "--master-port", that change will break the user script that used "--master".
See: https://docs.python.org/3.4/library/argparse.html#argument-abbreviations-prefix-matching
"""
# This if statement comes from the superclass implementation -- it precludes a code path in the superclass
# that is responsible for checking for argument prefixes. The return value of an empty list is the way that
# this method communicates no valid arguments were found.
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
return []
return super()._get_option_tuples(option_string)
示例11: __call__
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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()
示例12: error
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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)
示例13: add
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
def add(self, *args, **kwargs):
default = kwargs.get('default')
dtype = kwargs.get('type')
if dtype is None:
if default is None:
dtype = str
else:
dtype = type(default)
typename = dtype.__name__
if 'metavar' not in kwargs:
# metavar: display --foo <float=0.05> in help string
if 'choices' in kwargs:
choices = kwargs['choices']
choices_str = '/'.join(['{}']*len(choices)).format(*choices)
kwargs['metavar'] = '<{}: {}>'.format(typename, choices_str)
elif 'nargs' in kwargs:
# better formatting handled in _SingleMetavarFormatter
kwargs['metavar'] = '{}'.format(typename)
elif not kwargs.get('action'):
# if 'store_true', then no metavar needed
# list of actions: https://docs.python.org/3/library/argparse.html#action
default_str = '={}'.format(default) if default else ''
kwargs['metavar'] = '<{}{}>'.format(typename, default_str)
self.parser.add_argument(*args, **kwargs)
示例14: parse_args
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
def parse_args(args):
"""
Takes in the command-line arguments list (args), and returns a nice argparse
result with fields for all the options.
Borrows heavily from the argparse documentation examples:
<http://docs.python.org/library/argparse.html>
"""
# The command line arguments start with the program name, which we don't
# want to treat as an argument for argparse. So we remove it.
args = args[1:]
# Construct the parser (which is stored in parser)
# Module docstring lives in __doc__
# See http://python-forum.com/pythonforum/viewtopic.php?f=3&t=36847
# And a formatter class so our examples in the docstring look good. Isn't it
# convenient how we already wrapped it to 80 characters?
# See http://docs.python.org/library/argparse.html#formatter-class
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
# Now add all the options to it
parser.add_argument("avdl", type=argparse.FileType('r'),
help="the AVDL file to read")
return parser.parse_args(args)
示例15: parse_args
# 需要導入模塊: import argparse [as 別名]
# 或者: from argparse import html [as 別名]
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