Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active May 24, 2021 17:29
Show Gist options
  • Save drmalex07/9995807 to your computer and use it in GitHub Desktop.
Save drmalex07/9995807 to your computer and use it in GitHub Desktop.
A typical example of Python's argparse combined with configparser . #python #argparse #configparser
import os
import logging
import argparse
import ConfigParser as configparser
from paste.deploy.converters import asbool, asint, aslist
#
# Declare expected command-line arguments
#
argp = argparse.ArgumentParser()
# Add positional arguments (many)
argp.add_argument ("inputs", metavar='INFILE', type=str, nargs='+',
help='Provide input logs to parse and load into database');
# Add an optional string argument 'config'
argp.add_argument ("-c", "--config", dest='config_file', default='config.ini', type=str);
# Add a optional switch (boolean optional argument)
argp.add_argument ("-v", "--verbose", dest='verbose', default=False, action='store_true',
help='Be verbose');
# Parse command line
args = argp.parse_args()
#
# Parse a config ini-style file
#
here = os.path.realpath('.')
config_file = args.config_file
logging.info('Reading configuration from %s' %(config_file))
config = configparser.ConfigParser(defaults = {'here': here})
config.read(args.config_file)
# Do something with them
if args.verbose:
logging.info('Will produce verbose output')
sqla_url = config.get('main', 'sqlalchemy_url')
@kaislahattu
Copy link

I will also chime in with MestreLion, this is not a typical use case. Like he said, the preferred order is to have a set of hardcoded configuration parameters in the code, which will first get overwritten by config.ini file and finally the command line arguments have the highest priority and they will overwrite whatever has been specified. You are missing the hardcoded configuration parameter data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment