XClose
Menu

Argparse

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

In [1]:
%%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)
Writing greeter.py
In [2]:
%%bash
#!/usr/bin/env bash
chmod u+x greeter.py
In [3]:
%%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
In [4]:
%%bash
./greeter.py James Hetherington
Hey, James Hetherington.
In [5]:
%%bash
./greeter.py --polite James Hetherington
How do you do, James Hetherington.
In [6]:
%%bash
./greeter.py James Hetherington --title Dr
Hey, Dr James Hetherington.
In [ ]: