Skip to content

Instantly share code, notes, and snippets.

@aliceinwire
Last active December 23, 2015 23:39
Show Gist options
  • Save aliceinwire/17ef3920d062202118a9 to your computer and use it in GitHub Desktop.
Save aliceinwire/17ef3920d062202118a9 to your computer and use it in GitHub Desktop.
import argparse
import ConfigParser
conf_parser = argparse.ArgumentParser(
# Turn off help, so we print all options in response to -h
add_help=False
)
conf_parser.add_argument("-c", "--conf_file",
help="Specify config file", metavar="FILE")
args, remaining_argv = conf_parser.parse_known_args()
defaults = {
"default1" : "foo",
}
if args.conf_file:
config = ConfigParser.SafeConfigParser()
config.read([args.conf_file])
defaults = dict(config.items("Defaults"))
# Don't surpress 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("-default1","--default1", help="foo default option 1")
parser.add_argument("-default2","--default2",action='store_true', help="no argument option 2")
args = parser.parse_args(remaining_argv)
print args
@aliceinwire
Copy link
Author

default argument and config parser that i use in many projects

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