## Libraries: Command Lines, HTTP Requests and Databases * Click (http://click.pocoo.org/) * Requests (http://docs.python-requests.org/ * Python Database API (https://www.python.org/dev/peps/pep-0249/) --- ## Command Line Arguments What we want: ``` $ python greet.py Jane Hello, Jane! ``` ``` $ python greet.py --reverse Jane Hello, enaJ! ``` --- ## Why Use a Library for This? Let's try without a library: ```python import sys # sys.argv is a list of arguments to our program. # sys.argv[0] is the name of the program (greet.py), so we need sys.argv[1] name = sys.argv[1] print('Hello, {}!'.format(name)) ``` ``` $ python greet.py Jane Hello, Jane! ``` It works? But how about `--reverse`? --- ## Let's Still Not Use a Library ```python import sys opts = {'reverse': False} args = [] for arg in sys.argv[1]: if arg.startswith('-'): if arg == '--reverse': opts['reverse'] = True else: print('Unknown option {!r}'.format(arg), file=sys.stderr) else: uhm... ``` Eh, I give up. Let's just use a library already. --- ## Let's Use Click ```python import click @click.command() @click.argument('name') def main(name): print('Hello, {}!'.format(name)) main() ``` ```bash $ python greet.py Jane Hello, Jane! ``` ```bash $ python greet.py --reverse Jane Error: no such option: --reverse ``` --- ## Adding an Option ```python import click @click.command() @click.argument('name') @click.option('--reverse', is_flag=True, help='Reverse name.') def main(name, reverse): if reverse: name = name[::-1] print('Hello, {}!'.format(name)) main() ``` ```bash $ python greet.py --help Usage: greet.py [OPTIONS] NAME Options: --reverse Reverse name. --help Show this message and exit. ``` ```bash $ python greet.py --reverse Jane Hello, enaJ! ``` --- ## Requests: HTTP for Humans ```python import requests response = requests.get('http://google.com/') print(response.ok) print(response.text[:60]) ``` ```python True