Created
March 21, 2010 05:09
-
-
Save cosmin/339108 to your computer and use it in GitHub Desktop.
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
# saner syntax for optparse add_option | |
import os | |
def make_option_maker(parser, cmdline_prefix="", env_prefix="", dest_prefix=""): | |
"""Return a function that can be used to add_option with saner syntax. | |
Arguments: | |
parser: the parser object that will be used by the returned function | |
cmdline_prefix: will be used together with the name to build the command | |
line option. a suffix of -- and a prefix of - will be added so you | |
do not need to include those (--cmdline_prefix-<name>) | |
env_prefix: will be used together with the name to specify the environment | |
variable from which the option will default (ENV_PREFIX_<NAME>) | |
dest_prefix: will be used together with name to specify the variable name | |
in which the value of the option will be stored | |
Example: | |
parser = OptionParser() | |
omaker = make_option_maker(parser, dest_prefix = "someprefix", | |
env_prefix = "SOMEPREFIX", | |
cmdline_prefix = "someprefix") | |
omaker('foo', action="append", help="collect a list of foo") | |
omaker('bar', help="store bar", default="Blah") | |
""" | |
env_prefix = env_prefix.upper() | |
if cmdline_prefix and not cmdline_prefix.endswith("-"): | |
cmdline_prefix += "-" | |
if env_prefix and not env_prefix.endswith("_"): | |
env_prefix += "_" | |
if dest_prefix and not dest_prefix.endswith("_"): | |
dest_prefix += "_" | |
def option_maker(name, action = "store", help = "", default = None): | |
"""Use the given name, action and help string to add an option""" | |
if default is None: | |
_default = os.environ.get(env_prefix + name.upper()) | |
else: | |
_default = default | |
parser.add_option("--" + cmdline_prefix + name.lower(), | |
action = action, dest = dest_prefix + name.lower(), | |
default= _default, | |
help = help + " [" + env_prefix + name.upper() + "]") | |
return option_maker |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment