SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
Command line arguments
that make you smile
!

@martinmelin
!

martin@tictail.com
Command line arguments
that make you smile :-)
!

@martinmelin
!

martin@tictail.com
$ python --version	
Python 2.7.5
$ python --version	
Python 2.7.5
UI for your
command-line program
Who still writes
command-line programs?
Everyone should
But we usually just call them scripts
Scripts are awesome
Very few things are actually one-offs
One-off scripts
spread knowledge
Similar things can be solved by looking at old scripts
Scripts save
you from yourself
$ one-off-script.py	
RuntimeError: Stupid mistake
Scripts are much
better with arguments
$ one-off-script.py --dry-run	
RuntimeError: Stupid mistake
... but adding arguments
is painful, so we don’t
It doesn't have to be
but first, the status quo:
argparse
standard library recommendation
$ python prog.py -h	
usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)
Let’s parse!
import argparse	
!

parser = argparse.ArgumentParser(	
	 description='Process some integers.')	
!
import argparse	
!

parser = argparse.ArgumentParser(	
	 description='Process some integers.')	
!

parser.add_argument(	
	 'integers',	
	 metavar='N',	
	 type=int,	
	 nargs='+',	
	 help='an integer for the accumulator')	
!
import argparse	

!
parser = argparse.ArgumentParser(	
	 description='Process some integers.')	

!
parser.add_argument(	
	 'integers',	
	 metavar='N',	
	 type=int,	
	 nargs='+',	
	 help='an integer for the accumulator')	

!
parser.add_argument(	
	 '--sum',	
	 dest='accumulate',	
	 action='store_const',	
	 const=sum,	
	 default=max,	
	 help='sum the integers (default: find the max)')	

!
import argparse	

!
parser = argparse.ArgumentParser(	
	 description='Process some integers.')	

!
parser.add_argument(	
	 'integers',	
	 metavar='N',	
	 type=int,	
	 nargs='+',	
	 help='an integer for the accumulator')	

!
parser.add_argument(	
	 '--sum',	
	 dest='accumulate',	
	 action='store_const',	
	 const=sum,	
	 default=max,	
	 help='sum the integers (default: find the max)')	

!
args = parser.parse_args()
import argparse	

!
parser = argparse.ArgumentParser(	
	 description='Process some integers.')	

!
parser.add_argument(	
	 'integers',	
	 metavar='N',	
	 type=int,	
	 nargs='+',	
	 help='an integer for the accumulator')	

!
parser.add_argument(	
	 '--sum',	
	 dest='accumulate',	
	 action='store_const',	
	 const=sum,	
	 default=max,	
	 help='sum the integers (default: find the max)')	

!
args = parser.parse_args()
... and we're done
Phew!
!

All that ugly code for:
prog.py [-h] [--sum] N [N ...]
There's a better way!
Better practices™
docopt
made by Vladimir Keleshev
$ python prog.py -h	
usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)
Let's parse!
"""usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)	
"""
"""usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)	
"""	
import docopt
"""usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)	
"""	
import docopt	
!

args = docopt.docopt(__doc__)
... and we're done
$ python prog.py --sum 1 2 3	
{'--help': False,	
'--sum': True,	
'N': ['1', '2', '3']}
$ python prog.py --sum 1 2 3	
{'--help': False,	
'--sum': True,	
'N': ['1', '2', '3']}	
!

$ python prog.py --help	
usage: prog.py [-h] [--sum] N [N ...]	
!

Process some integers.	
!

positional arguments:	
N
an integer for the accumulator	
!

optional arguments:	
-h, --help show this help message and exit	
--sum
sum the integers (default:	
find the max)
Write for humans,
let the computer figure it out
Write scripts
!
Write scripts
Use docopt
Write scripts
Use docopt
Smile :-)
Thanks!
!

@martinmelin
!

martin@tictail.com

Mais conteúdo relacionado

Mais procurados

Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
Jimmy Schementi
 

Mais procurados (20)

Perl Tidy Perl Critic
Perl Tidy Perl CriticPerl Tidy Perl Critic
Perl Tidy Perl Critic
 
PyWPS Development restart
PyWPS Development restartPyWPS Development restart
PyWPS Development restart
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
 
Machine Learning on Code - SF meetup
Machine Learning on Code - SF meetupMachine Learning on Code - SF meetup
Machine Learning on Code - SF meetup
 
C language header files
C language header filesC language header files
C language header files
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Perl Modules
Perl ModulesPerl Modules
Perl Modules
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Write Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 HoursWrite Your Own Compiler in 24 Hours
Write Your Own Compiler in 24 Hours
 
Lua Study Share
Lua Study ShareLua Study Share
Lua Study Share
 
Python 3000
Python 3000Python 3000
Python 3000
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
 
Python Loop
Python LoopPython Loop
Python Loop
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
 
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+EuroPython 2017 - Bonono - Simple ETL in python 3.5+
EuroPython 2017 - Bonono - Simple ETL in python 3.5+
 
Python Functions 1
Python Functions 1Python Functions 1
Python Functions 1
 
Gore: Go REPL
Gore: Go REPLGore: Go REPL
Gore: Go REPL
 

Destaque

Perl Intro 9 Command Line Arguments
Perl Intro 9 Command Line ArgumentsPerl Intro 9 Command Line Arguments
Perl Intro 9 Command Line Arguments
Shaun Griffith
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
myrajendra
 
B&i2013 donderdag 14.15_zaal_c_the freedom of form and material
B&i2013 donderdag 14.15_zaal_c_the freedom of form and materialB&i2013 donderdag 14.15_zaal_c_the freedom of form and material
B&i2013 donderdag 14.15_zaal_c_the freedom of form and material
Bouwmaterialen_Innovatie
 
B&i2013 donderdag 14.15_zaal_b_biobased composieten
B&i2013 donderdag 14.15_zaal_b_biobased composietenB&i2013 donderdag 14.15_zaal_b_biobased composieten
B&i2013 donderdag 14.15_zaal_b_biobased composieten
Bouwmaterialen_Innovatie
 
B&i2013 donderdag 12.00_zaal_d_concepthouse
B&i2013 donderdag 12.00_zaal_d_concepthouseB&i2013 donderdag 12.00_zaal_d_concepthouse
B&i2013 donderdag 12.00_zaal_d_concepthouse
Bouwmaterialen_Innovatie
 
How to Avoid the ‘Making Stuff'’ Approach
How to Avoid the ‘Making Stuff'’ ApproachHow to Avoid the ‘Making Stuff'’ Approach
How to Avoid the ‘Making Stuff'’ Approach
Sarah Liddemore
 
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaalB&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
Bouwmaterialen_Innovatie
 

Destaque (20)

Docopt
DocoptDocopt
Docopt
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Perl Intro 9 Command Line Arguments
Perl Intro 9 Command Line ArgumentsPerl Intro 9 Command Line Arguments
Perl Intro 9 Command Line Arguments
 
Perl Intro 4 Debugger
Perl Intro 4 DebuggerPerl Intro 4 Debugger
Perl Intro 4 Debugger
 
Geographic Computation in Perl
Geographic Computation in PerlGeographic Computation in Perl
Geographic Computation in Perl
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
B&i2013 donderdag 14.15_zaal_c_the freedom of form and material
B&i2013 donderdag 14.15_zaal_c_the freedom of form and materialB&i2013 donderdag 14.15_zaal_c_the freedom of form and material
B&i2013 donderdag 14.15_zaal_c_the freedom of form and material
 
Angus gidley baird_australia's_agriculture_future_2
Angus gidley baird_australia's_agriculture_future_2Angus gidley baird_australia's_agriculture_future_2
Angus gidley baird_australia's_agriculture_future_2
 
B&i2013 donderdag 14.15_zaal_b_biobased composieten
B&i2013 donderdag 14.15_zaal_b_biobased composietenB&i2013 donderdag 14.15_zaal_b_biobased composieten
B&i2013 donderdag 14.15_zaal_b_biobased composieten
 
B&i2013 donderdag 12.00_zaal_d_concepthouse
B&i2013 donderdag 12.00_zaal_d_concepthouseB&i2013 donderdag 12.00_zaal_d_concepthouse
B&i2013 donderdag 12.00_zaal_d_concepthouse
 
0469131019 nguyen chibao.doc
0469131019 nguyen chibao.doc0469131019 nguyen chibao.doc
0469131019 nguyen chibao.doc
 
Utah Data Center Project
Utah Data Center ProjectUtah Data Center Project
Utah Data Center Project
 
Beat the heat at palm springs golf clubs
Beat the heat at palm springs golf clubsBeat the heat at palm springs golf clubs
Beat the heat at palm springs golf clubs
 
How to Avoid the ‘Making Stuff'’ Approach
How to Avoid the ‘Making Stuff'’ ApproachHow to Avoid the ‘Making Stuff'’ Approach
How to Avoid the ‘Making Stuff'’ Approach
 
Improving quality teaching and learning in higher education (eu recommendations)
Improving quality teaching and learning in higher education (eu recommendations)Improving quality teaching and learning in higher education (eu recommendations)
Improving quality teaching and learning in higher education (eu recommendations)
 
Tu delft lecture-tall-buildings3
Tu delft lecture-tall-buildings3Tu delft lecture-tall-buildings3
Tu delft lecture-tall-buildings3
 
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaalB&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
B&i2013 donderdag 13.45_zaal_c_symbiose tussen licht en materiaal
 
Introducing SocialRank
Introducing SocialRankIntroducing SocialRank
Introducing SocialRank
 
Improving quality teching and learning in higher education (eu reccommendatio...
Improving quality teching and learning in higher education (eu reccommendatio...Improving quality teching and learning in higher education (eu reccommendatio...
Improving quality teching and learning in higher education (eu reccommendatio...
 
GOLD - IEEE GOLD Volunteer Information Evening Nov 2013
GOLD - IEEE GOLD Volunteer Information Evening Nov 2013GOLD - IEEE GOLD Volunteer Information Evening Nov 2013
GOLD - IEEE GOLD Volunteer Information Evening Nov 2013
 

Semelhante a Command line arguments that make you smile

Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
Bryan O'Sullivan
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
Go Asgard
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
vibrantuser
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Model
guest2a5acfb
 

Semelhante a Command line arguments that make you smile (20)

Python basic
Python basicPython basic
Python basic
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
 
Boost.Python - domesticating the snake
Boost.Python - domesticating the snakeBoost.Python - domesticating the snake
Boost.Python - domesticating the snake
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
 
The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184The Ring programming language version 1.5.3 book - Part 39 of 184
The Ring programming language version 1.5.3 book - Part 39 of 184
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
app4.pptx
app4.pptxapp4.pptx
app4.pptx
 
Danny Adair - Python Cookbook - Intro
Danny Adair - Python Cookbook - IntroDanny Adair - Python Cookbook - Intro
Danny Adair - Python Cookbook - Intro
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Model
 
effective_r27
effective_r27effective_r27
effective_r27
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMP
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Command line arguments that make you smile