Argparse

Argparse

This is the standard library for building programs with a command-line interface.

%%writefile greeter.py
#!/usr/bin/env python
from argparse import ArgumentParser

if __name__ == "__main__":
    parser = ArgumentParser(description="Generate appropriate greetings")
    parser.add_argument("--title", "-t")
    parser.add_argument("--polite", "-p", action="store_true")
    parser.add_argument("personal")
    parser.add_argument("family")
    arguments = parser.parse_args()

    greeting = "How do you do, " if arguments.polite else "Hey, "
    if arguments.title:
        greeting += arguments.title + " "
    greeting += arguments.personal + " " + arguments.family + "."
    print(greeting)
Overwriting greeter.py
%%bash
#!/usr/bin/env bash
#%%cmd (windows)
chmod u+x greeter.py
%%bash
./greeter.py --help
usage: greeter.py [-h] [--title TITLE] [--polite] personal family

Generate appropriate greetings

positional arguments:
  personal
  family

optional arguments:
  -h, --help            show this help message and exit
  --title TITLE, -t TITLE
  --polite, -p
%%bash
./greeter.py James Hetherington
Hey, James Hetherington.
%%bash
./greeter.py --polite James Hetherington
How do you do, James Hetherington.
%%bash
./greeter.py James Hetherington --title Dr
Hey, Dr James Hetherington.