Skip to content

Instantly share code, notes, and snippets.

@tantale
Created April 26, 2016 19:06
Show Gist options
  • Save tantale/bd7548b449eaa36704182f8cc5e53869 to your computer and use it in GitHub Desktop.
Save tantale/bd7548b449eaa36704182f8cc5e53869 to your computer and use it in GitHub Desktop.
Using mutually exclusive options with argparse
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
parser = argparse.ArgumentParser("my_app")
ini_level_group = parser.add_mutually_exclusive_group()
ini_level_group.add_argument("--system", dest="ini_level", action="store_const", const="system",
help="Get or set application level configuration")
ini_level_group.add_argument("--global", dest="ini_level", action="store_const", const="global",
help="Get or set user level configuration")
ini_level_group.add_argument("--local", dest="ini_level", action="store_const", const="local",
help="Get or set project level configuration")
parser.set_defaults(ini_level="local")
args = parser.parse_args(["--system"])
print(args)
# Namespace(ini_level='system')
args = parser.parse_args(["--system", "--global"])
# usage: my_app [-h] [--system | --global | --local]
# my_app: error: argument --global: not allowed with argument --system
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment