SlideShare una empresa de Scribd logo
1 de 9
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Genetic_Algorithm_AI(TU)
Genetic_Algorithm_AI(TU)Genetic_Algorithm_AI(TU)
Genetic_Algorithm_AI(TU)
Kapil Khatiwada
 
NLP, Expert system and pattern recognition
NLP, Expert system and pattern recognitionNLP, Expert system and pattern recognition
NLP, Expert system and pattern recognition
Mohammad Ilyas Malik
 
Principles of soft computing-Associative memory networks
Principles of soft computing-Associative memory networksPrinciples of soft computing-Associative memory networks
Principles of soft computing-Associative memory networks
Sivagowry Shathesh
 
engineeringmathematics-iv_unit-ii
engineeringmathematics-iv_unit-iiengineeringmathematics-iv_unit-ii
engineeringmathematics-iv_unit-ii
Kundan Kumar
 

La actualidad más candente (20)

Perceptron 2015.ppt
Perceptron 2015.pptPerceptron 2015.ppt
Perceptron 2015.ppt
 
recurrence relations
 recurrence relations recurrence relations
recurrence relations
 
Handwritten Digit Recognition(Convolutional Neural Network) PPT
Handwritten Digit Recognition(Convolutional Neural Network) PPTHandwritten Digit Recognition(Convolutional Neural Network) PPT
Handwritten Digit Recognition(Convolutional Neural Network) PPT
 
Genetic_Algorithm_AI(TU)
Genetic_Algorithm_AI(TU)Genetic_Algorithm_AI(TU)
Genetic_Algorithm_AI(TU)
 
Bruteforce algorithm
Bruteforce algorithmBruteforce algorithm
Bruteforce algorithm
 
Predicate logic
 Predicate logic Predicate logic
Predicate logic
 
Artificial Intelligence Notes Unit 4
Artificial Intelligence Notes Unit 4Artificial Intelligence Notes Unit 4
Artificial Intelligence Notes Unit 4
 
Template Matching - Pattern Recognition
Template Matching - Pattern RecognitionTemplate Matching - Pattern Recognition
Template Matching - Pattern Recognition
 
NLP, Expert system and pattern recognition
NLP, Expert system and pattern recognitionNLP, Expert system and pattern recognition
NLP, Expert system and pattern recognition
 
Mc culloch pitts neuron
Mc culloch pitts neuronMc culloch pitts neuron
Mc culloch pitts neuron
 
27 NP Completness
27 NP Completness27 NP Completness
27 NP Completness
 
Principles of soft computing-Associative memory networks
Principles of soft computing-Associative memory networksPrinciples of soft computing-Associative memory networks
Principles of soft computing-Associative memory networks
 
Adaptive Resonance Theory
Adaptive Resonance TheoryAdaptive Resonance Theory
Adaptive Resonance Theory
 
Fuzzy inference systems
Fuzzy inference systemsFuzzy inference systems
Fuzzy inference systems
 
A Note on Leapfrog Integration
A Note on Leapfrog IntegrationA Note on Leapfrog Integration
A Note on Leapfrog Integration
 
Neural Networks on Steroids (Poster)
Neural Networks on Steroids (Poster)Neural Networks on Steroids (Poster)
Neural Networks on Steroids (Poster)
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Clique Relaxation Models in Networks: Theory, Algorithms, and Applications
Clique Relaxation Models in Networks: Theory, Algorithms, and ApplicationsClique Relaxation Models in Networks: Theory, Algorithms, and Applications
Clique Relaxation Models in Networks: Theory, Algorithms, and Applications
 
Counter propagation Network
Counter propagation NetworkCounter propagation Network
Counter propagation Network
 
engineeringmathematics-iv_unit-ii
engineeringmathematics-iv_unit-iiengineeringmathematics-iv_unit-ii
engineeringmathematics-iv_unit-ii
 

Destacado

Festival de coplas de sexto
Festival de coplas de sextoFestival de coplas de sexto
Festival de coplas de sexto
Logos Academy
 
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridosCopilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Alejandra Araujo
 
Invitación navideña
Invitación navideñaInvitación navideña
Invitación navideña
andre15vacas
 
8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog
GUALUPITAPLCS
 
Formas literarias
Formas literariasFormas literarias
Formas literarias
MaryAcostaA
 

Destacado (20)

Proyecto Rescate de los valores.
Proyecto Rescate de los valores.Proyecto Rescate de los valores.
Proyecto Rescate de los valores.
 
Festival de coplas de sexto
Festival de coplas de sextoFestival de coplas de sexto
Festival de coplas de sexto
 
Coplas sobre los apodos
Coplas sobre los   apodosCoplas sobre los   apodos
Coplas sobre los apodos
 
Poemas y canciones para sexto C
Poemas y canciones para sexto CPoemas y canciones para sexto C
Poemas y canciones para sexto C
 
Retahilas por mayra rodriguez
Retahilas  por mayra rodriguezRetahilas  por mayra rodriguez
Retahilas por mayra rodriguez
 
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridosCopilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
 
Cartelera informativa terra hidro
Cartelera informativa terra hidroCartelera informativa terra hidro
Cartelera informativa terra hidro
 
Invitación navideña
Invitación navideñaInvitación navideña
Invitación navideña
 
Folleto terrahidro
Folleto terrahidroFolleto terrahidro
Folleto terrahidro
 
De sabios, de poetas y de locos...
De sabios, de poetas y de locos...De sabios, de poetas y de locos...
De sabios, de poetas y de locos...
 
Chile
ChileChile
Chile
 
8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog8.9.inventario de fuentes en el blog
8.9.inventario de fuentes en el blog
 
Adivinanzas
AdivinanzasAdivinanzas
Adivinanzas
 
Cartilla talleres socializacion Bunny Bonita
Cartilla talleres socializacion Bunny BonitaCartilla talleres socializacion Bunny Bonita
Cartilla talleres socializacion Bunny Bonita
 
Formas literarias
Formas literariasFormas literarias
Formas literarias
 
Retahilas infantiles
Retahilas infantilesRetahilas infantiles
Retahilas infantiles
 
Cartilla
CartillaCartilla
Cartilla
 
Folklore
FolkloreFolklore
Folklore
 
Folclor
FolclorFolclor
Folclor
 
Maria dolores coplas retahilas amorfinos
Maria dolores coplas retahilas amorfinosMaria dolores coplas retahilas amorfinos
Maria dolores coplas retahilas amorfinos
 

Similar a Argparse: Python command line parser

Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
Bryan O'Sullivan
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
shravs_188
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
Timo Stollenwerk
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
UFPA
 

Similar a Argparse: Python command line parser (20)

The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
 
Ch2
Ch2Ch2
Ch2
 
Day3
Day3Day3
Day3
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
 
Qt Translations
Qt TranslationsQt Translations
Qt Translations
 
Python for Scientists
Python for ScientistsPython for Scientists
Python for Scientists
 
Command line arguments that make you smile
Command line arguments that make you smileCommand line arguments that make you smile
Command line arguments that make you smile
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet
PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet
PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet
 
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)Functional Thinking for Java Developers (presented in Javafest Bengaluru)
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
week-12x
week-12xweek-12x
week-12x
 
ZCA: A component architecture for Python
ZCA: A component architecture for PythonZCA: A component architecture for Python
ZCA: A component architecture for Python
 
Diving deep into twig
Diving deep into twigDiving deep into twig
Diving deep into twig
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 

Más de Timo Stollenwerk

Einführung Test-driven Development
Einführung Test-driven DevelopmentEinführung Test-driven Development
Einführung Test-driven Development
Timo Stollenwerk
 

Más de Timo Stollenwerk (20)

German Aerospace Center (DLR) Web Relaunch
German Aerospace Center (DLR) Web RelaunchGerman Aerospace Center (DLR) Web Relaunch
German Aerospace Center (DLR) Web Relaunch
 
Performance Testing (Python Barcamp Cologne 2020)
Performance Testing (Python Barcamp Cologne 2020)Performance Testing (Python Barcamp Cologne 2020)
Performance Testing (Python Barcamp Cologne 2020)
 
Python & JavaScript
Python & JavaScriptPython & JavaScript
Python & JavaScript
 
Roadmap to a Headless Plone
Roadmap to a Headless PloneRoadmap to a Headless Plone
Roadmap to a Headless Plone
 
Plone.restapi - a bridge to the modern web
Plone.restapi - a bridge to the modern webPlone.restapi - a bridge to the modern web
Plone.restapi - a bridge to the modern web
 
Divide et impera
Divide et imperaDivide et impera
Divide et impera
 
The Butler and The Snake (Europython 2015)
The Butler and The Snake (Europython 2015)The Butler and The Snake (Europython 2015)
The Butler and The Snake (Europython 2015)
 
Hypermedia APIs mit Javascript und Python
Hypermedia APIs mit Javascript und PythonHypermedia APIs mit Javascript und Python
Hypermedia APIs mit Javascript und Python
 
Plone Testing & Continuous Integration Team Report 2014
Plone Testing & Continuous Integration Team Report 2014Plone Testing & Continuous Integration Team Report 2014
Plone Testing & Continuous Integration Team Report 2014
 
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
The Beauty and the Beast - Modern Javascript Development with AngularJS and P...
 
The Butler and the Snake - JCICPH
The Butler and the Snake - JCICPHThe Butler and the Snake - JCICPH
The Butler and the Snake - JCICPH
 
The Butler and the Snake - Continuous Integration for Python
The Butler and the Snake - Continuous Integration for PythonThe Butler and the Snake - Continuous Integration for Python
The Butler and the Snake - Continuous Integration for Python
 
AngularJS & Plone
AngularJS & PloneAngularJS & Plone
AngularJS & Plone
 
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
Who let the robot out? Qualitativ hochwertige Software durch Continuous Integ...
 
Plone5
Plone5Plone5
Plone5
 
Who let the robot out? - Building high quality software with Continuous Integ...
Who let the robot out? - Building high quality software with Continuous Integ...Who let the robot out? - Building high quality software with Continuous Integ...
Who let the robot out? - Building high quality software with Continuous Integ...
 
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...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...
 
Plone Einführung
Plone EinführungPlone Einführung
Plone Einführung
 
Einführung Test-driven Development
Einführung Test-driven DevelopmentEinführung Test-driven Development
Einführung Test-driven Development
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[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
 
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...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 

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