SlideShare a Scribd company logo
1 of 18
Download to read offline
Dizionario Italiano a cura di Enrico Olivetti
CLI Applications
What's wrong with scripts?
Why CLI Applications?
1. Argparse
2. Click
3. Docopt
print("This is important code")
1
2
for index, arg in enumerate(sys.argv):
3
print(f"[{index}]: {arg}")
4
What's Wrong with Scripts?
Easy to get started
Limited possibilities for structure
Hard to (unit) test
No dependency management
Deployment may require care
Custom user experience
print("Usage: foo <bar> --baz")
def main():
1
2
3
if __name__ == "__main__":
4
main()
5
Why CLI Applications?
Standardized user experience
More possibilities for structure
Possibilities for all kinds of testing
Dependency management
Packaging & distribution
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()
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Argparse
import click
@click.command()
@click.version_option()
@click.argument('filename')
def main(filename):
click.echo(filename)
1
2
3
4
5
6
7
Click
import click
@click.command()
@click.version_option()
@click.argument('filename', type=click.Path(exists=True))
def main(filename):
click.echo(filename)
1
2
3
4
5
6
7
import click
@click.command()
@click.version_option()
@click.argument('infile', type=click.File())
def main(infile):
click.echo(infile.read())
1
2
3
4
5
6
7
"""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'],
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Docopt
$ copier gh:painless-software/python-cli-test-helpers pycon-italia-cli
🎤 engine
(Use arrow keys)
» Argparse
Click
Docopt
...
Demo
🐍 ✨
✨
https://python-cli-test-helpers.readthedocs.io
Thank you!
for your precious time
Painless Software
Less pain, more fun.
Most images taken from Wikipedia (CC-SA)
Alberto Sordi animated GIF stolen from giffetteria.it

More Related Content

Similar to PyCon 23: Smettiamola di scrivere script

External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLAntony T Curtis
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88Mahmoud Samir Fayed
 
Mock cli with Python unittest
Mock cli with Python unittestMock cli with Python unittest
Mock cli with Python unittestSong Jin
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...7mind
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review ProcessDr. Syed Hassan Amin
 
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법GangSeok Lee
 
Suite Script 2.0 API Basics
Suite Script 2.0 API BasicsSuite Script 2.0 API Basics
Suite Script 2.0 API BasicsJimmy Butare
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 
How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]Devon Bernard
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guideAdy Liu
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection7mind
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with RMartin Jung
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKonstantin Sorokin
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 

Similar to PyCon 23: Smettiamola di scrivere script (20)

External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQL
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88The Ring programming language version 1.3 book - Part 60 of 88
The Ring programming language version 1.3 book - Part 60 of 88
 
Mock cli with Python unittest
Mock cli with Python unittestMock cli with Python unittest
Mock cli with Python unittest
 
Shell Script Tutorial
Shell Script TutorialShell Script Tutorial
Shell Script Tutorial
 
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
distage: Purely Functional Staged Dependency Injection; bonus: Faking Kind Po...
 
Improving Code Quality Through Effective Review Process
Improving Code Quality Through Effective  Review ProcessImproving Code Quality Through Effective  Review Process
Improving Code Quality Through Effective Review Process
 
.net Framework
.net Framework.net Framework
.net Framework
 
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
[2009 CodeEngn Conference 03] koheung - 윈도우 커널 악성코드에 대한 분석 및 방법
 
Suite Script 2.0 API Basics
Suite Script 2.0 API BasicsSuite Script 2.0 API Basics
Suite Script 2.0 API Basics
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
11i Logs
11i Logs11i Logs
11i Logs
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 

More from Peter Bittner

APPUiO Quick Start (OpenShift > DevOps > App Dev)
APPUiO Quick Start (OpenShift > DevOps > App Dev)APPUiO Quick Start (OpenShift > DevOps > App Dev)
APPUiO Quick Start (OpenShift > DevOps > App Dev)Peter Bittner
 
Pee Dee Kay (PDK) - Puppet Development Kit
Pee Dee Kay (PDK) - Puppet Development KitPee Dee Kay (PDK) - Puppet Development Kit
Pee Dee Kay (PDK) - Puppet Development KitPeter Bittner
 
EuroPython 2019: Modern Continuous Delivery for Python Developers
EuroPython 2019: Modern Continuous Delivery for Python DevelopersEuroPython 2019: Modern Continuous Delivery for Python Developers
EuroPython 2019: Modern Continuous Delivery for Python DevelopersPeter Bittner
 
Avoid the Vendor Lock-in Trap (with App Deployment)
Avoid the Vendor Lock-in Trap (with App Deployment)Avoid the Vendor Lock-in Trap (with App Deployment)
Avoid the Vendor Lock-in Trap (with App Deployment)Peter Bittner
 
A guide to modern software development 2018
A guide to modern software development 2018A guide to modern software development 2018
A guide to modern software development 2018Peter Bittner
 
PyCon 9: Continuous Delivery starts at your Development Dnvironment
PyCon 9: Continuous Delivery starts at your Development DnvironmentPyCon 9: Continuous Delivery starts at your Development Dnvironment
PyCon 9: Continuous Delivery starts at your Development DnvironmentPeter Bittner
 
Painless Continuous Delivery – DjangoCon 2017
Painless Continuous Delivery – DjangoCon 2017Painless Continuous Delivery – DjangoCon 2017
Painless Continuous Delivery – DjangoCon 2017Peter Bittner
 
Continuous Delivery for Python Developers – PyCon Otto
Continuous Delivery for Python Developers – PyCon OttoContinuous Delivery for Python Developers – PyCon Otto
Continuous Delivery for Python Developers – PyCon OttoPeter Bittner
 
Fix-Price Projects And Agile – PyCon Sette
Fix-Price Projects And Agile – PyCon SetteFix-Price Projects And Agile – PyCon Sette
Fix-Price Projects And Agile – PyCon SettePeter Bittner
 
Creating a Collaboration Platform (Leveraging the Django Eco System)
Creating a Collaboration Platform (Leveraging the Django Eco System)Creating a Collaboration Platform (Leveraging the Django Eco System)
Creating a Collaboration Platform (Leveraging the Django Eco System)Peter Bittner
 
Linux für Einsteiger und UmsteigerInnen (Vortrag)
Linux für Einsteiger und UmsteigerInnen (Vortrag)Linux für Einsteiger und UmsteigerInnen (Vortrag)
Linux für Einsteiger und UmsteigerInnen (Vortrag)Peter Bittner
 

More from Peter Bittner (13)

APPUiO Quick Start (OpenShift > DevOps > App Dev)
APPUiO Quick Start (OpenShift > DevOps > App Dev)APPUiO Quick Start (OpenShift > DevOps > App Dev)
APPUiO Quick Start (OpenShift > DevOps > App Dev)
 
Pee Dee Kay (PDK) - Puppet Development Kit
Pee Dee Kay (PDK) - Puppet Development KitPee Dee Kay (PDK) - Puppet Development Kit
Pee Dee Kay (PDK) - Puppet Development Kit
 
Managing 100+ WAFs
Managing 100+ WAFsManaging 100+ WAFs
Managing 100+ WAFs
 
EuroPython 2019: Modern Continuous Delivery for Python Developers
EuroPython 2019: Modern Continuous Delivery for Python DevelopersEuroPython 2019: Modern Continuous Delivery for Python Developers
EuroPython 2019: Modern Continuous Delivery for Python Developers
 
Avoid the Vendor Lock-in Trap (with App Deployment)
Avoid the Vendor Lock-in Trap (with App Deployment)Avoid the Vendor Lock-in Trap (with App Deployment)
Avoid the Vendor Lock-in Trap (with App Deployment)
 
A guide to modern software development 2018
A guide to modern software development 2018A guide to modern software development 2018
A guide to modern software development 2018
 
PyCon 9: Continuous Delivery starts at your Development Dnvironment
PyCon 9: Continuous Delivery starts at your Development DnvironmentPyCon 9: Continuous Delivery starts at your Development Dnvironment
PyCon 9: Continuous Delivery starts at your Development Dnvironment
 
Painless Continuous Delivery – DjangoCon 2017
Painless Continuous Delivery – DjangoCon 2017Painless Continuous Delivery – DjangoCon 2017
Painless Continuous Delivery – DjangoCon 2017
 
Continuous Delivery for Python Developers – PyCon Otto
Continuous Delivery for Python Developers – PyCon OttoContinuous Delivery for Python Developers – PyCon Otto
Continuous Delivery for Python Developers – PyCon Otto
 
Fix-Price Projects And Agile – PyCon Sette
Fix-Price Projects And Agile – PyCon SetteFix-Price Projects And Agile – PyCon Sette
Fix-Price Projects And Agile – PyCon Sette
 
Creating a Collaboration Platform (Leveraging the Django Eco System)
Creating a Collaboration Platform (Leveraging the Django Eco System)Creating a Collaboration Platform (Leveraging the Django Eco System)
Creating a Collaboration Platform (Leveraging the Django Eco System)
 
Linux für Einsteiger und UmsteigerInnen (Vortrag)
Linux für Einsteiger und UmsteigerInnen (Vortrag)Linux für Einsteiger und UmsteigerInnen (Vortrag)
Linux für Einsteiger und UmsteigerInnen (Vortrag)
 
Linux auf meinem PC
Linux auf meinem PCLinux auf meinem PC
Linux auf meinem PC
 

Recently uploaded

What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Recently uploaded (20)

What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

PyCon 23: Smettiamola di scrivere script

  • 1.
  • 2.
  • 3. Dizionario Italiano a cura di Enrico Olivetti
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11. CLI Applications What's wrong with scripts? Why CLI Applications? 1. Argparse 2. Click 3. Docopt
  • 12. print("This is important code") 1 2 for index, arg in enumerate(sys.argv): 3 print(f"[{index}]: {arg}") 4 What's Wrong with Scripts? Easy to get started Limited possibilities for structure Hard to (unit) test No dependency management Deployment may require care Custom user experience
  • 13. print("Usage: foo <bar> --baz") def main(): 1 2 3 if __name__ == "__main__": 4 main() 5 Why CLI Applications? Standardized user experience More possibilities for structure Possibilities for all kinds of testing Dependency management Packaging & distribution
  • 14. 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() ... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Argparse
  • 15. import click @click.command() @click.version_option() @click.argument('filename') def main(filename): click.echo(filename) 1 2 3 4 5 6 7 Click import click @click.command() @click.version_option() @click.argument('filename', type=click.Path(exists=True)) def main(filename): click.echo(filename) 1 2 3 4 5 6 7 import click @click.command() @click.version_option() @click.argument('infile', type=click.File()) def main(infile): click.echo(infile.read()) 1 2 3 4 5 6 7
  • 16. """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'], ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Docopt
  • 17. $ copier gh:painless-software/python-cli-test-helpers pycon-italia-cli 🎤 engine (Use arrow keys) » Argparse Click Docopt ... Demo 🐍 ✨ ✨ https://python-cli-test-helpers.readthedocs.io
  • 18. Thank you! for your precious time Painless Software Less pain, more fun. Most images taken from Wikipedia (CC-SA) Alberto Sordi animated GIF stolen from giffetteria.it