A simple on–off option

We will define a simple on–off option with a one-letter short name or a longer name. We should also provide an explicit action. We might want to provide a destination variable if we omit the longer name, or if the longer name is unpleasant as a Python variable. Let's set this up using the following code:

parser.add_argument(
'-v', '--verbose', action='store_true', default=False)

This will define the long and short versions of the command-line option. If the option is present, the action will set the verbose option to True. If the option is absent, the verbose option will default to False. Here are some common variations of this theme:

  • We might change the action to 'store_false' with a default of True.
  • Sometimes, we'll have a default of None instead of True or False.
  • Sometimes, we'll use an action of 'store_const' with an additional const= argument. This allows us to move beyond simple Boolean values and store things such as logging levels or other objects.
  • We might also have an action of 'count', which allows the option to get repeated, increasing the count. In this case, the default is often zero.

If we're using the logger, we might define a debugging option like the following code:

parser.add_argument( 
'--debug', action='store_const', const=logging.DEBUG,
default=logging.INFO, dest="logging_level" )

We changed the action to store_const, which stores a constant value and provides a specific constant value of logging.DEBUG. This means that the resulting options object will directly provide the value needed to configure the root logger. We can then simply configure the logger using config.logging_level without any further mapping or conditional processing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset