Forked from gene1wood/config_file_and_command_line_arguments.py
Created
April 14, 2023 18:55
-
-
Save virtadpt/bad5a98d3d2379df683b27c06b0193e9 to your computer and use it in GitHub Desktop.
An example of how to use a config file which is overridden by command line arguments in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import ConfigParser | |
import argparse | |
import logging | |
import os | |
def type_loglevel(level): | |
try: | |
result = getattr(logging, level.upper()) | |
except AttributeError: | |
raise argparse.ArgumentTypeError("'%s' is not a valid log level. Please use %s" % | |
(level, | |
[x for x in logging._levelNames.keys() | |
if isinstance(x, str)])) | |
return result | |
if __name__=='__main__': | |
conf_parser = argparse.ArgumentParser( | |
# Turn off help, so we print all options in response to -h | |
add_help=False | |
) | |
conf_parser.add_argument("-c", "--config", | |
help="Specify a configuration file", | |
metavar="FILE") | |
args, remaining_argv = conf_parser.parse_known_args() | |
defaults = { | |
"foo" : "default foo value", | |
"bar" : "default bar value", | |
"baz" : "default baz value", | |
"loglevel" : "INFO" | |
} | |
if args.config: | |
config = ConfigParser.SafeConfigParser(defaults) | |
config.read([args.config]) | |
defaults = dict(config.items("Defaults")) | |
for key in defaults.keys(): | |
if "\n" in defaults[key]: | |
defaults[key] = [x.strip() for x in defaults[key].splitlines()] | |
# Don't suppress add_help here so it will handle -h | |
parser = argparse.ArgumentParser( | |
# Inherit options from config_parser | |
parents=[conf_parser], | |
# print script description with -h/--help | |
description=__doc__, | |
# Don't mess with format of description | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
) | |
parser.set_defaults(**defaults) | |
parser.add_argument('-f', '--foo', | |
help="Foo") | |
parser.add_argument('-b', '--bar', | |
help="Bar") | |
parser.add_argument('-z', '--baz', | |
help="Baz") | |
parser.add_argument('-l', '--loglevel', type=type_loglevel, | |
help='Log level verbosity') | |
args = parser.parse_args(remaining_argv) | |
logging.basicConfig(level=args.loglevel) | |
print args |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment