otherwise you get this ...
you want this ...
They help your command line python script interpret the options and arguments given to it on the command line.
args.py file.txt
args.py -h file2.py
args.py --verbose file3.txt
Technically speaking, they help your python program interpret the list containing the arguments passed to your script on the command line. This can be accessed with sys.argv as shown below
# %load args.py
#!/usr/bin/env python
import sys
print(sys.argv)
So what does the output from the program above look like when executed like this:
./args.py file.txt
['./args.py', 'file.txt']
./args.py -h file2.py
['./args.py', '-h', 'file2.py']
./args.py --verbose file3.txt
['./args.py', '--verbose', 'file3.txt']
It's just a Python list.
These libraries help you interpret that list and do things like generate sensible help messages and argument validation.
# %load add-1.py
#!/usr/bin/env python
import click
def add(a, b):
return float(a) + float(b)
@click.command()
@click.argument('a', nargs=1)
@click.argument('b', nargs=1)
def main(a, b):
print(add(a, b))
if __name__ == '__main__':
main()
./add-1.py --help
Usage: add-1.py [OPTIONS] A B
Options:
--help Show this message and exit.
# %load add.py
#!/usr/bin/env python
import click
def add(a, b):
return float(a) + float(b)
@click.command()
@click.argument('a', nargs=1, type=click.FLOAT)
@click.argument('b', nargs=1, type=click.FLOAT)
@click.option('--verbose', '-v', is_flag=True, default=False,
help="generate verbose output")
def main(a, b, verbose):
"""Docstring thing"""
if verbose:
print("a: %s" % a)
print("b: %s" % b)
print(add(a, b))
if __name__ == '__main__':
main()
./add.py --help
Usage: add.py [OPTIONS] A B
Docstring thing
Options:
-v, --verbose generate verbose output
--help Show this message and exit.