bayespy.utils.misc.parse_command_line_arguments

bayespy.utils.misc.parse_command_line_arguments(mandatory_args, *optional_args_list, argv=None)[source]

Parse command line arguments of style “–parameter=value”.

Parameter specification is tuple: (name, converter, description).

Some special handling:

  • If converter is None, the command line does not accept any value for it, but instead use either “–option” to enable or “–no-option” to disable.

  • If argument name contains hyphens, those are converted to underscores in the keys of the returned dictionaries.

Parameters:
  • mandatory_args (list of tuples) – Specs for mandatory arguments

  • optional_args_list (list of lists of tuples) – Specs for each optional arguments set

  • argv (list of strings (optional)) – The command line arguments. By default, read sys.argv.

Returns:

  • args (dictionary) – The parsed mandatory arguments

  • kwargs (dictionary) – The parsed optional arguments

Examples

>>> from pprint import pprint as print
>>> from bayespy.utils import misc
>>> (args, kwargs) = misc.parse_command_line_arguments(
...     # Mandatory arguments
...     [
...         ('name',     str,  "Full name"),
...         ('age',      int,  "Age (years)"),
...         ('employed', None, "Working"),
...     ],
...     # Optional arguments
...     [
...         ('phone',          str, "Phone number"),
...         ('favorite-color', str, "Favorite color")
...     ],
...     argv=['--name=John Doe',
...           '--age=42',
...           '--no-employed',
...           '--favorite-color=pink']
... )
>>> print(args)
{'age': 42, 'employed': False, 'name': 'John Doe'}
>>> print(kwargs)
{'favorite_color': 'pink'}

It is possible to have several optional argument sets:

>>> (args, kw_info, kw_fav) = misc.parse_command_line_arguments(
...     # Mandatory arguments
...     [
...         ('name',     str,  "Full name"),
...     ],
...     # Optional arguments (contact information)
...     [
...         ('phone', str, "Phone number"),
...         ('email', str, "E-mail address")
...     ],
...     # Optional arguments (preferences)
...     [
...         ('favorite-color', str, "Favorite color"),
...         ('favorite-food',  str, "Favorite food")
...     ],
...     argv=['--name=John Doe',
...           '--favorite-color=pink',
...           '--email=john.doe@email.com',
...           '--favorite-food=spaghetti']
... )
>>> print(args)
{'name': 'John Doe'}
>>> print(kw_info)
{'email': 'john.doe@email.com'}
>>> print(kw_fav)
{'favorite_color': 'pink', 'favorite_food': 'spaghetti'}