SlideShare a Scribd company logo
2
Most read
Argparse: Python command line parser


              Timo Stollenwerk


               April 27th, 2009




        Timo Stollenwerk   Argparse: Python command line parser
Introduction




      makes writing command line tools in Python easy
      just briey describe your command line interface
      argparse will take care of the rest, including:
          parsing the arguments and ags from sys.argv
          converting arg strings into objects for your program
          formatting and printing any help messages
          and much more ...




                     Timo Stollenwerk   Argparse: Python command line parser
Optparse vs. Argparse




      handling positional arguments
      supporting sub-commands
      allowing alternative option prexes like + and /
      handling zero-or-more and one-or-more style arguments
      producing more informative usage messages
      providing a much simpler interface for custom types and
      actions




                     Timo Stollenwerk   Argparse: Python command line parser
Installation




   easy_install argparse




                 Timo Stollenwerk   Argparse: Python command line parser
ArgumentParser




   i m p o r t a r g p a r s e
   p a r s e r = a r g p a r s e . A r g u m e n t P a r s e r (
   ...        d e s c r i p t i o n ='A f o o t h a t b a r s ' )
   p a r s e r . p r i n t _ h e l p ( )
  u s a g e : a r g p a r s e . py [ − h ]

  A foo that bars

  o p t i o n a l a rg um en ts :
    −h , −− h e l p show t h i s h e l p message and e x i t




                           Timo Stollenwerk   Argparse: Python command line parser
The add_argument() method




  optional argument (myscript.py -f)
   p a r s e r . add_argument ( ' − f ' , '−− foo ' )

  positional argument (myscript.py foo bar)
   p a r s e r . add_argument ( ' arg1 ' )
   p a r s e r . add_argument ( ' arg2 ' )




                      Timo Stollenwerk   Argparse: Python command line parser
The parse_args() method




  myscript.py -a foo -s
   p a r s e r . add_argument ( ' − a ' , '−− add ' ,
   ...        a c t i o n =' append ' , n a r g s =1)
   p a r s e r . add_argument ( ' − s ' , '−− show ' ,
   ...        a c t i o n =' s t o r e _ t r u e ' )
   a r g s = p a r s e r . p a r s e _ a r g s ( )
   p r i n t a r g s . add
  foo
   p r i n t a r g s . show
  True




                      Timo Stollenwerk   Argparse: Python command line parser
A more complex example

  sum.py 2 3


  p a r s e r = a r g p a r s e . ArgumentParser (
          d e s c r i p t i o n ='Sum t h e i n t e g e r s . ' )

  p a r s e r . add_argument (
      ' i n t e g e r s ' , metavar =' i n t ' , t y p e=i n t , n a r g s = '+ ' ,
      h e l p =' one o f t h e i n t e g e r s t o be summed ' )
  p a r s e r . add_argument (
     '−− l o g ' , t y p e=a r g p a r s e . F i l e T y p e ( 'w ' ) , d e f a u l t=s y s .
      h e l p =' t h e f i l e where t h e sum s h o u l d be w r i t t e n '
                 ' ( d e f a u l t : w r i t e t h e sum t o s t d o u t ) ' )

  args = parser . parse_args ()
  a r g s . l o g . w r i t e ( '% s n ' % sum ( a r g s . i n t e g e r s ) )
  args . log . close ()
                           Timo Stollenwerk   Argparse: Python command line parser
Futher Information




      http://argparse.googlecode.com




                     Timo Stollenwerk   Argparse: Python command line parser
Ad

Recommended

Basic concepts for python web development
Basic concepts for python web development
NexSoftsys
 
C union
C union
muhammadsarab
 
Cache performance considerations
Cache performance considerations
Slideshare
 
Web spam
Web spam
Prakash Dubey
 
Web search vs ir
Web search vs ir
Primya Tamil
 
16829 memory management2
16829 memory management2
Sidharth Sundaresan
 
107年交通部主計業務研討會講義
107年交通部主計業務研討會講義
nofearing
 
C Programming : Pointers and Strings
C Programming : Pointers and Strings
Selvaraj Seerangan
 
Basic web security model
Basic web security model
Prachi Gulihar
 
Information retrieval 8 term weighting
Information retrieval 8 term weighting
Vaibhav Khanna
 
File handling in c
File handling in c
aakanksha s
 
Timing Diagram.pptx
Timing Diagram.pptx
ISMT College
 
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Tom Cappetta
 
02. input validation module v5
02. input validation module v5
Eoin Keary
 
Information Security Lecture Notes
Information Security Lecture Notes
FellowBuddy.com
 
Variables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
String handling in_java
String handling in_java
774474
 
COA (Unit_1.pptx)
COA (Unit_1.pptx)
Thapar Institute
 
Ethical Hacking - sniffing
Ethical Hacking - sniffing
Bhavya Chawla
 
computer architecture lab manual
computer architecture lab manual
Neelamani Samal
 
C++ programming function
C++ programming function
Vishalini Mugunen
 
Structure
Structure
Rokonuzzaman Rony
 
Array Of Pointers
Array Of Pointers
Sharad Dubey
 
Sistem Basis Data 1
Sistem Basis Data 1
Mrirfan
 
Pointers in C
Pointers in C
guestdc3f16
 
Analisis Semantik - P6
Analisis Semantik - P6
ahmad haidaroh
 
Algorithms and flowcharts ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..
Nagendra N
 
Operand and Opcode | Computer Science
Operand and Opcode | Computer Science
Transweb Global Inc
 
Proyecto Rescate de los valores.
Proyecto Rescate de los valores.
pablovalerocpe
 
Festival de coplas de sexto
Festival de coplas de sexto
Logos Academy
 

More Related Content

What's hot (20)

Basic web security model
Basic web security model
Prachi Gulihar
 
Information retrieval 8 term weighting
Information retrieval 8 term weighting
Vaibhav Khanna
 
File handling in c
File handling in c
aakanksha s
 
Timing Diagram.pptx
Timing Diagram.pptx
ISMT College
 
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Tom Cappetta
 
02. input validation module v5
02. input validation module v5
Eoin Keary
 
Information Security Lecture Notes
Information Security Lecture Notes
FellowBuddy.com
 
Variables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
String handling in_java
String handling in_java
774474
 
COA (Unit_1.pptx)
COA (Unit_1.pptx)
Thapar Institute
 
Ethical Hacking - sniffing
Ethical Hacking - sniffing
Bhavya Chawla
 
computer architecture lab manual
computer architecture lab manual
Neelamani Samal
 
C++ programming function
C++ programming function
Vishalini Mugunen
 
Structure
Structure
Rokonuzzaman Rony
 
Array Of Pointers
Array Of Pointers
Sharad Dubey
 
Sistem Basis Data 1
Sistem Basis Data 1
Mrirfan
 
Pointers in C
Pointers in C
guestdc3f16
 
Analisis Semantik - P6
Analisis Semantik - P6
ahmad haidaroh
 
Algorithms and flowcharts ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..
Nagendra N
 
Operand and Opcode | Computer Science
Operand and Opcode | Computer Science
Transweb Global Inc
 
Basic web security model
Basic web security model
Prachi Gulihar
 
Information retrieval 8 term weighting
Information retrieval 8 term weighting
Vaibhav Khanna
 
File handling in c
File handling in c
aakanksha s
 
Timing Diagram.pptx
Timing Diagram.pptx
ISMT College
 
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Cyber Range - An Open-Source Offensive / Defensive Learning Environment on AWS
Tom Cappetta
 
02. input validation module v5
02. input validation module v5
Eoin Keary
 
Information Security Lecture Notes
Information Security Lecture Notes
FellowBuddy.com
 
Variables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
String handling in_java
String handling in_java
774474
 
Ethical Hacking - sniffing
Ethical Hacking - sniffing
Bhavya Chawla
 
computer architecture lab manual
computer architecture lab manual
Neelamani Samal
 
Sistem Basis Data 1
Sistem Basis Data 1
Mrirfan
 
Analisis Semantik - P6
Analisis Semantik - P6
ahmad haidaroh
 
Algorithms and flowcharts ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..
Nagendra N
 
Operand and Opcode | Computer Science
Operand and Opcode | Computer Science
Transweb Global Inc
 

Viewers also liked (20)

Proyecto Rescate de los valores.
Proyecto Rescate de los valores.
pablovalerocpe
 
Festival de coplas de sexto
Festival de coplas de sexto
Logos Academy
 
Coplas sobre los apodos
Coplas sobre los apodos
Aura Maria Melendez Campos
 
Poemas y canciones para sexto C
Poemas y canciones para sexto C
Romysand
 
Retahilas por mayra rodriguez
Retahilas por mayra rodriguez
mayra_rodriguez
 
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Alejandra Araujo
 
Cartelera informativa terra hidro
Cartelera informativa terra hidro
andre15vacas
 
Invitación navideña
Invitación navideña
andre15vacas
 
Folleto terrahidro
Folleto terrahidro
andre15vacas
 
De sabios, de poetas y de locos...
De sabios, de poetas y de locos...
ali16enero
 
Chile
Chile
MM Couve
 
8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog
GUALUPITAPLCS
 
Adivinanzas
Adivinanzas
Ana Estela Brito Zavala
 
Cartilla talleres socializacion Bunny Bonita
Cartilla talleres socializacion Bunny Bonita
nachoxavy
 
Formas literarias
Formas literarias
MaryAcostaA
 
Retahilas infantiles
Retahilas infantiles
purifran
 
Cartilla
Cartilla
Jenny Milena
 
Folklore
Folklore
Lorenzo Sanches
 
Folclor
Folclor
kekiiita
 
Maria dolores coplas retahilas amorfinos
Maria dolores coplas retahilas amorfinos
Brigitte Jimenez de Coronel
 
Proyecto Rescate de los valores.
Proyecto Rescate de los valores.
pablovalerocpe
 
Festival de coplas de sexto
Festival de coplas de sexto
Logos Academy
 
Poemas y canciones para sexto C
Poemas y canciones para sexto C
Romysand
 
Retahilas por mayra rodriguez
Retahilas por mayra rodriguez
mayra_rodriguez
 
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Alejandra Araujo
 
Cartelera informativa terra hidro
Cartelera informativa terra hidro
andre15vacas
 
Invitación navideña
Invitación navideña
andre15vacas
 
Folleto terrahidro
Folleto terrahidro
andre15vacas
 
De sabios, de poetas y de locos...
De sabios, de poetas y de locos...
ali16enero
 
8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog
GUALUPITAPLCS
 
Cartilla talleres socializacion Bunny Bonita
Cartilla talleres socializacion Bunny Bonita
nachoxavy
 
Formas literarias
Formas literarias
MaryAcostaA
 
Retahilas infantiles
Retahilas infantiles
purifran
 
Ad

Similar to Argparse: Python command line parser (20)

Command line arguments that make you smile
Command line arguments that make you smile
Martin Melin
 
Howto argparse
Howto argparse
Manuel Cueto
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
Docopt
Docopt
René Ribaud
 
Python assignment help
Python assignment help
www.myassignmenthelp.net
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
Rodrigo Senra
 
Python programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
Python1_Extracted_PDF_20250404_1054.pptx
Python1_Extracted_PDF_20250404_1054.pptx
ecomwithfaith
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Python ppt
Python ppt
Anush verma
 
Learning python
Learning python
Hoang Nguyen
 
Learning python
Learning python
Harry Potter
 
Learning python
Learning python
Tony Nguyen
 
Learning python
Learning python
Luis Goldster
 
Learning python
Learning python
James Wong
 
Learning python
Learning python
Young Alista
 
Learning python
Learning python
Fraboni Ec
 
python_strings.pdf
python_strings.pdf
rajendraprasadbabub1
 
inputoutput.pptx
inputoutput.pptx
Venkateswara Babu Ravipati
 
Command line arguments that make you smile
Command line arguments that make you smile
Martin Melin
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
Rodrigo Senra
 
Python1_Extracted_PDF_20250404_1054.pptx
Python1_Extracted_PDF_20250404_1054.pptx
ecomwithfaith
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
Learning python
Learning python
James Wong
 
Learning python
Learning python
Fraboni Ec
 
Ad

More from Timo Stollenwerk (20)

German Aerospace Center (DLR) Web Relaunch
German Aerospace Center (DLR) Web Relaunch
Timo Stollenwerk
 
Performance Testing (Python Barcamp Cologne 2020)
Performance Testing (Python Barcamp Cologne 2020)
Timo Stollenwerk
 
Python & JavaScript
Python & JavaScript
Timo Stollenwerk
 
Roadmap to a Headless Plone
Roadmap to a Headless Plone
Timo Stollenwerk
 
Plone.restapi - a bridge to the modern web
Plone.restapi - a bridge to the modern web
Timo Stollenwerk
 
Divide et impera
Divide et impera
Timo Stollenwerk
 
The Butler and The Snake (Europython 2015)
The Butler and The Snake (Europython 2015)
Timo Stollenwerk
 
Hypermedia APIs mit Javascript und Python
Hypermedia APIs mit Javascript und Python
Timo Stollenwerk
 
Plone Testing & Continuous Integration Team Report 2014
Plone Testing & Continuous Integration Team Report 2014
Timo Stollenwerk
 
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
Timo Stollenwerk
 
The Butler and the Snake - JCICPH
The Butler and the Snake - JCICPH
Timo Stollenwerk
 
The Butler and the Snake - Continuous Integration for Python
The Butler and the Snake - Continuous Integration for Python
Timo Stollenwerk
 
AngularJS & Plone
AngularJS & Plone
Timo Stollenwerk
 
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Timo Stollenwerk
 
Plone5
Plone5
Timo Stollenwerk
 
Who let the robot out? - Building high quality software with Continuous Integ...
Who let the robot out? - Building high quality software with Continuous Integ...
Timo Stollenwerk
 
The Future Is Written - Building next generation Plone sites with plone.app.c...
The Future Is Written - Building next generation Plone sites with plone.app.c...
Timo Stollenwerk
 
Plone Einführung
Plone Einführung
Timo Stollenwerk
 
Einführung Test-driven Development
Einführung Test-driven Development
Timo Stollenwerk
 
Test-Driven Development
Test-Driven Development
Timo Stollenwerk
 
German Aerospace Center (DLR) Web Relaunch
German Aerospace Center (DLR) Web Relaunch
Timo Stollenwerk
 
Performance Testing (Python Barcamp Cologne 2020)
Performance Testing (Python Barcamp Cologne 2020)
Timo Stollenwerk
 
Roadmap to a Headless Plone
Roadmap to a Headless Plone
Timo Stollenwerk
 
Plone.restapi - a bridge to the modern web
Plone.restapi - a bridge to the modern web
Timo Stollenwerk
 
The Butler and The Snake (Europython 2015)
The Butler and The Snake (Europython 2015)
Timo Stollenwerk
 
Hypermedia APIs mit Javascript und Python
Hypermedia APIs mit Javascript und Python
Timo Stollenwerk
 
Plone Testing & Continuous Integration Team Report 2014
Plone Testing & Continuous Integration Team Report 2014
Timo Stollenwerk
 
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
Timo Stollenwerk
 
The Butler and the Snake - JCICPH
The Butler and the Snake - JCICPH
Timo Stollenwerk
 
The Butler and the Snake - Continuous Integration for Python
The Butler and the Snake - Continuous Integration for Python
Timo Stollenwerk
 
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Timo Stollenwerk
 
Who let the robot out? - Building high quality software with Continuous Integ...
Who let the robot out? - Building high quality software with Continuous Integ...
Timo Stollenwerk
 
The Future Is Written - Building next generation Plone sites with plone.app.c...
The Future Is Written - Building next generation Plone sites with plone.app.c...
Timo Stollenwerk
 
Einführung Test-driven Development
Einführung Test-driven Development
Timo Stollenwerk
 

Recently uploaded (20)

High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
“Key Requirements to Successfully Implement Generative AI in Edge Devices—Opt...
Edge AI and Vision Alliance
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 

Argparse: Python command line parser

  • 1. Argparse: Python command line parser Timo Stollenwerk April 27th, 2009 Timo Stollenwerk Argparse: Python command line parser
  • 2. Introduction makes writing command line tools in Python easy just briey describe your command line interface argparse will take care of the rest, including: parsing the arguments and ags from sys.argv converting arg strings into objects for your program formatting and printing any help messages and much more ... Timo Stollenwerk Argparse: Python command line parser
  • 3. Optparse vs. Argparse handling positional arguments supporting sub-commands allowing alternative option prexes like + and / handling zero-or-more and one-or-more style arguments producing more informative usage messages providing a much simpler interface for custom types and actions Timo Stollenwerk Argparse: Python command line parser
  • 4. Installation easy_install argparse Timo Stollenwerk Argparse: Python command line parser
  • 5. ArgumentParser i m p o r t a r g p a r s e p a r s e r = a r g p a r s e . A r g u m e n t P a r s e r ( ... d e s c r i p t i o n ='A f o o t h a t b a r s ' ) p a r s e r . p r i n t _ h e l p ( ) u s a g e : a r g p a r s e . py [ − h ] A foo that bars o p t i o n a l a rg um en ts : −h , −− h e l p show t h i s h e l p message and e x i t Timo Stollenwerk Argparse: Python command line parser
  • 6. The add_argument() method optional argument (myscript.py -f) p a r s e r . add_argument ( ' − f ' , '−− foo ' ) positional argument (myscript.py foo bar) p a r s e r . add_argument ( ' arg1 ' ) p a r s e r . add_argument ( ' arg2 ' ) Timo Stollenwerk Argparse: Python command line parser
  • 7. The parse_args() method myscript.py -a foo -s p a r s e r . add_argument ( ' − a ' , '−− add ' , ... a c t i o n =' append ' , n a r g s =1) p a r s e r . add_argument ( ' − s ' , '−− show ' , ... a c t i o n =' s t o r e _ t r u e ' ) a r g s = p a r s e r . p a r s e _ a r g s ( ) p r i n t a r g s . add foo p r i n t a r g s . show True Timo Stollenwerk Argparse: Python command line parser
  • 8. A more complex example sum.py 2 3 p a r s e r = a r g p a r s e . ArgumentParser ( d e s c r i p t i o n ='Sum t h e i n t e g e r s . ' ) p a r s e r . add_argument ( ' i n t e g e r s ' , metavar =' i n t ' , t y p e=i n t , n a r g s = '+ ' , h e l p =' one o f t h e i n t e g e r s t o be summed ' ) p a r s e r . add_argument ( '−− l o g ' , t y p e=a r g p a r s e . F i l e T y p e ( 'w ' ) , d e f a u l t=s y s . h e l p =' t h e f i l e where t h e sum s h o u l d be w r i t t e n ' ' ( d e f a u l t : w r i t e t h e sum t o s t d o u t ) ' ) args = parser . parse_args () a r g s . l o g . w r i t e ( '% s n ' % sum ( a r g s . i n t e g e r s ) ) args . log . close () Timo Stollenwerk Argparse: Python command line parser
  • 9. Futher Information http://argparse.googlecode.com Timo Stollenwerk Argparse: Python command line parser