Integrating command-line options and environment variables

The general policy for environment variables is to provide configuration inputs, similar to command-line options and arguments. For the most part, we use environment variables for settings that rarely change. We'll often set them via the .bashrc or .bash_profile files so that the values are set every time we log in. We may set the environment variables more globally in an /etc/bashrc file so that they apply to all users. We can also set environment variables on the command line, but these settings only apply to the program being run.

In some cases, all of our configuration settings can be provided on the command line. In this case, the environment variables could be used as a kind of backup syntax for slowly changing variables.

In other cases, the configuration values providing environment variables may be disconnected from the configuration performed by command-line options. We may need to get some values from the environment and merge in values that come from the command line.

We can leverage environment variables to set the default values in a configuration object. We want to gather these values prior to parsing the command-line arguments. This way, command-line arguments can override environment variables. There are two common approaches to this:

  • Explicitly setting the values when defining the command-line options: This has the advantage of making the default value show up in the help message. It only works for environment variables that overlap with command-line options. We might do something like the following to use the SIM_SAMPLES environment variable to provide a default value that can be overridden:
parser.add_argument( 
"--samples",
action="store", default=int(os.environ.get("SIM_SAMPLES",100)), type=int,
help="Samples to generate")
  • Implicitly setting the values as part of the parsing process: This makes it simple to merge environment variables with command-line options into a single configuration. We can populate a namespace with default values and then overwrite it with the parsed values from the command line. This provides us with three levels of option values: the default defined in the parser, an override value seeded into the namespace, and finally, any override value provided on the command line, as shown in the following code:
config4 = argparse.Namespace() 
config4.samples = int(os.environ.get("SIM_SAMPLES",100)) 
config4a = parser.parse_args(sys.argv[1:], namespace=config4) 
The argument parser can perform type conversions for values that are not simple strings. However, gathering environment variables doesn't automatically involve a type conversion. For options that have non-string values, we must perform the type conversion in our application.
..................Content has been hidden....................

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