ubelt.util_arg module

Simple ways to interact with the commandline without defining a full blown CLI

ubelt.util_arg.argval(key, default=NoParam, argv=None)[source]

Get the value of a keyword argument specified on the command line.

Values can be specified as <key> <value> or <key>=<value>

Parameters:
  • key (str or tuple) – string or tuple of strings. Each key should be prefixed with two hyphens (i.e. )
  • default (Optional[object]) – value to return if not specified
  • argv (Optional[list]) – overrides sys.argv if specified
Returns:

value : the value specified after the key. It they key is

specified multiple times, then the first value is returned.

Return type:

str

Todo

  • [ ] Can we handle the case where the value is a list of long paths?
  • [ ] Should we default the first or last specified instance of the flag.

Example

>>> import ubelt as ub
>>> argv = ['--ans', '42', '--quest=the grail', '--ans=6', '--bad']
>>> assert ub.argval('--spam', argv=argv) == ub.NoParam
>>> assert ub.argval('--quest', argv=argv) == 'the grail'
>>> assert ub.argval('--ans', argv=argv) == '42'
>>> assert ub.argval('--bad', argv=argv) == ub.NoParam
>>> assert ub.argval(('--bad', '--bar'), argv=argv) == ub.NoParam

Example

>>> # Test fix for GH Issue #41
>>> import ubelt as ub
>>> argv = ['--path=/path/with/k=3']
>>> ub.argval('--path', argv=argv) == '/path/with/k=3'
ubelt.util_arg.argflag(key, argv=None)[source]

Determines if a key is specified on the command line

Parameters:
  • key (str or tuple) – string or tuple of strings. Each key should be prefixed with two hyphens (i.e. )
  • argv (Optional[list]) – overrides sys.argv if specified
Returns:

flag : True if the key (or any of the keys) was specified

Return type:

bool

Example

>>> import ubelt as ub
>>> argv = ['--spam', '--eggs', 'foo']
>>> assert ub.argflag('--eggs', argv=argv) is True
>>> assert ub.argflag('--ans', argv=argv) is False
>>> assert ub.argflag('foo', argv=argv) is True
>>> assert ub.argflag(('bar', '--spam'), argv=argv) is True