Skip to content

Instantly share code, notes, and snippets.

@Highstaker
Created May 31, 2016 13:31
Show Gist options
  • Save Highstaker/20b2490b18061e3337f139fe618f5f7c to your computer and use it in GitHub Desktop.
Save Highstaker/20b2490b18061e3337f139fe618f5f7c to your computer and use it in GitHub Desktop.
An example of how to use argparse module for Python
import argparse
parser = argparse.ArgumentParser()
# add a positional argument. THey are treated as strings by default
parser.add_argument("echo", help="echo the string you use here")
# tell it to treat the argument as an integer
parser.add_argument("square", help="display a square of a given number",
type=int
)
# an optional argument. type 1 to set it to true, 0 to False. Default is True
parser.add_argument("--verbosity", help="set output verbosity", type=int, default=1)
# simply specifying this argument makes it true. You can specify a short (-v) and long (--verbose) versions of an option
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
# specify possible values for an option
parser.add_argument("-l", "--level", help="the level",
type=int, choices=[0, 1, 2])
# returns how many times this option occurs. -ccc returns 3. Not specifying it returns None
parser.add_argument("-c", "--counter", action="count",
help="set counter")
# grouping to make options mutually exclusive. They cannot be used in the same command then.
group = parser.add_mutually_exclusive_group()
group.add_argument("-t", "--talk", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
group.add_argument("-s", "--silent", action="store_true")
# parse the arguments. They can be accessed in form args.argument
args = parser.parse_args()
print(args.echo)
print(args.square**2)
print("Verbosity is " + ("ON" if args.verbosity else "OFF"))
print("Verbosity is " + ("ON" if args.verbose else "OFF"))
print("Level is", args.level)
print("Counter is", args.counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment