Smettiamola di scrivere script!
PyCon 23
@peterbittner, django@bittner.it
Dizionario Italiano a cura di Enrico Olivetti
# CLI APPLICATIONS
print("This is important code")
for index, arg in enumerate(sys.argv):
print(f"[{index}]: {arg}")
# CLI APPLICATIONS
def main():
print("Usage: foo <bar> --baz")
if __name__ == "__main__":
main()
# CLI APPLICATIONS
import argparse
from . import __version__
def parse_arguments():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version', action='version',
version=__version__)
parser.add_argument('filename')
args = parser.parse_args()
return args
def main():
args = parse_arguments()
...
# CLI APPLICATIONS
import click
@click.command()
@click.version_option()
@click.argument('filename')
def main(filename):
click.echo(filename)
# CLI APPLICATIONS
import click
@click.command()
@click.version_option()
@click.argument('filename', type=click.Path(exists=True))
def main(filename):
click.echo(filename)
import click
@click.command()
@click.version_option()
@click.argument('infile', type=click.File())
def main(infile):
click.echo(infile.read())
"""Foobar
Usage:
foobar (-h | --help | --version)
foobar [-s | --silent] <file>
foobar [-v | --verbose] <file>
Positional arguments:
file target file path name
Optional arguments:
-h, --help show this help message and exit
-s, --silent don't show progress output
-v, --verbose explain progress verbosely
--version show program's version number and exit
"""
from docopt import docopt
from . import __version__
def parse_arguments():
args = docopt(__doc__, version=__version__)
return dict(
file=args['<file>'],
silent=args['-s'] or args['--silent'],
verbose=args['-v'] or args['--verbose'],
)
# CLI APPLICATIONS
$ copier gh:painless-software/python-cli-test-helpers pycon-italia-cli
🎤 engine
(Use arrow keys)
» Argparse
Click
Docopt
...
# WRITING TESTS
Less pain, more fun.
Most images taken from Wikipedia (CC-SA)
Alberto Sordi animated GIF stolen from giffetteria.it