Argparse

Please open notebook rsepython-s3r3.ipynb

This is the standard library for building programs with a command-line interface. Here we show a short introduction to it, but we recommend reading the official tutorial.

We will use this to create a program ‘greeter’, note that we have included help information.

%%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

If you are using MacOS or Linux, we need to change the file permissions so that we can execute our program:

%%bash
#!/usr/bin/env bash
chmod u+x greeter.py

We can view the program help information that we created:

%%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

If you are using Windows, change bash by cmd, and prepend the commands by python

%%cmd
python greeter.py UCL RITS

Let’s see our program in action:

%%bash
./greeter.py UCL RITS

Hey, UCL RITS.

%%bash
./greeter.py --polite UCL RITS

How do you do, UCL RITS.

%%bash
./greeter.py UCL RITS --title Dr

Hey, Dr UCL RITS.

Next: Reading - Packaging