Last active
August 29, 2015 14:14
-
-
Save gesquive/d4163b8926b141d4cbb8 to your computer and use it in GitHub Desktop.
Code snippet to parse arguments from a config file
This file contains 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
import argparse | |
import ConfigParser | |
import sys | |
def main(argv=None): | |
# Do argv default this way, as doing it in the functional | |
# declaration sets it at compile time. | |
if argv is None: | |
argv = sys.argv[1]: | |
# Parse any conf_file specification | |
# Found at: http://stackoverflow.com/a/5826167/613218 | |
# We make this parser with add_help=False so that | |
# it doesn't parse -h and print help. | |
config_parser = argparse.ArgumentParser( | |
description=__doc__, # printed with -h/--help | |
# Don't mess with format of description | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
# Turn off help, so we print all options in response to -h | |
add_help=False | |
) | |
config_parser.add_argument("-c", "--config-file", | |
help="Specify config file", metavar="FILE") | |
args, remaining_argv = conf_parser.parse_known_args(argv) | |
if args.config_file: | |
config = ConfigParser.SafeConfigParser() | |
config.read([args.config_file]) | |
defaults = dict(config.items("Defaults")) | |
else: | |
defaults = { "option":"default" } | |
# Parse rest of arguments | |
# Don't suppress add_help here so it will handle -h | |
parser = argparse.ArgumentParser( | |
# Inherit options from config_parser | |
parents=[config_parser] | |
) | |
parser.set_defaults(**defaults) | |
parser.add_argument("--option") | |
args = parser.parse_args(remaining_argv) | |
print "Option is \"{}\"".format(args.option) | |
return(0) | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment