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

More Related Content

PDF
Input and Output
PPT
python-message-0.1.0
PDF
ZCA: A component architecture for Python
PDF
ODP
The bones of a nice Python script
Input and Output
python-message-0.1.0
ZCA: A component architecture for Python
The bones of a nice Python script

What's hot (20)

PPTX
Build a compiler in 2hrs - NCrafts Paris 2015
PDF
PDF
Control Flow
PDF
Proxy OOP Pattern in PHP
PDF
Howto argparse
ODP
Programming Under Linux In Python
PPS
Bdd: Tdd and beyond the infinite
DOCX
Network security
PDF
Python and sysadmin I
RTF
DOCX
Auxiliary
PDF
Hacker Thursdays: An introduction to binary exploitation
PDF
Advanced perl finer points ,pack&unpack,eval,files
PDF
Learn Java Part 6
PDF
Learn Java Part 7
PDF
2Bytesprog2 course_2014_c1_sets
PPTX
Fourier project presentation
Build a compiler in 2hrs - NCrafts Paris 2015
Control Flow
Proxy OOP Pattern in PHP
Howto argparse
Programming Under Linux In Python
Bdd: Tdd and beyond the infinite
Network security
Python and sysadmin I
Auxiliary
Hacker Thursdays: An introduction to binary exploitation
Advanced perl finer points ,pack&unpack,eval,files
Learn Java Part 6
Learn Java Part 7
2Bytesprog2 course_2014_c1_sets
Fourier project presentation
Ad

Viewers also liked (20)

PDF
Proyecto Rescate de los valores.
PDF
Festival de coplas de sexto
DOC
Coplas sobre los apodos
PDF
Poemas y canciones para sexto C
PPTX
Retahilas por mayra rodriguez
DOCX
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
PDF
Cartelera informativa terra hidro
PDF
Invitación navideña
PDF
Folleto terrahidro
PPT
De sabios, de poetas y de locos...
PPT
Chile
PPTX
8.9.inventario de fuentes en el blog
PPT
PDF
Cartilla talleres socializacion Bunny Bonita
PPTX
Formas literarias
PPTX
Retahilas infantiles
DOC
Cartilla
DOC
Folklore
PPT
Folclor
DOCX
Maria dolores coplas retahilas amorfinos
Proyecto Rescate de los valores.
Festival de coplas de sexto
Coplas sobre los apodos
Poemas y canciones para sexto C
Retahilas por mayra rodriguez
Copilacion de refranes, calavera lírica, adivinanzas, copla y corridos
Cartelera informativa terra hidro
Invitación navideña
Folleto terrahidro
De sabios, de poetas y de locos...
Chile
8.9.inventario de fuentes en el blog
Cartilla talleres socializacion Bunny Bonita
Formas literarias
Retahilas infantiles
Cartilla
Folklore
Folclor
Maria dolores coplas retahilas amorfinos
Ad

Similar to Argparse: Python command line parser (20)

PPTX
Python1_Extracted_PDF_20250404_1054.pptx
PDF
PPTX
Basic of Python- Hands on Session
PDF
Real World Haskell: Lecture 7
PDF
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
PPTX
Qt Translations
PPTX
Python for Scientists
PDF
Command line arguments that make you smile
PPT
Pattern matching
PPT
Python - Getting to the Essence - Points.com - Dave Park
PDF
Free Monads Getting Started
ODP
PHP Web Programming
PDF
PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet
PDF
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
PDF
pa-pe-pi-po-pure Python Text Processing
PDF
Diving deep into twig
PDF
Porque aprender haskell me fez um programador python melhor?
PDF
Python cheat-sheet
Python1_Extracted_PDF_20250404_1054.pptx
Basic of Python- Hands on Session
Real World Haskell: Lecture 7
Presentation pythonpppppppppppppppppppppppppppppppppyyyyyyyyyyyyyyyyyyytttttt...
Qt Translations
Python for Scientists
Command line arguments that make you smile
Pattern matching
Python - Getting to the Essence - Points.com - Dave Park
Free Monads Getting Started
PHP Web Programming
PyData Paris 2015 - Track 3.2 Serge Guelton et Pierrick Brunet
Functional Thinking for Java Developers (presented in Javafest Bengaluru)
pa-pe-pi-po-pure Python Text Processing
Diving deep into twig
Porque aprender haskell me fez um programador python melhor?
Python cheat-sheet

More from Timo Stollenwerk (20)

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

Recently uploaded (20)

PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
Modernising the Digital Integration Hub
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
STKI Israel Market Study 2025 version august
PPT
What is a Computer? Input Devices /output devices
PDF
Architecture types and enterprise applications.pdf
PPTX
TEXTILE technology diploma scope and career opportunities
PPTX
Configure Apache Mutual Authentication
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
A proposed approach for plagiarism detection in Myanmar Unicode text
DOCX
search engine optimization ppt fir known well about this
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Modernising the Digital Integration Hub
A review of recent deep learning applications in wood surface defect identifi...
Enhancing plagiarism detection using data pre-processing and machine learning...
Custom Battery Pack Design Considerations for Performance and Safety
Getting started with AI Agents and Multi-Agent Systems
STKI Israel Market Study 2025 version august
What is a Computer? Input Devices /output devices
Architecture types and enterprise applications.pdf
TEXTILE technology diploma scope and career opportunities
Configure Apache Mutual Authentication
Consumable AI The What, Why & How for Small Teams.pdf
A proposed approach for plagiarism detection in Myanmar Unicode text
search engine optimization ppt fir known well about this
sustainability-14-14877-v2.pddhzftheheeeee
NewMind AI Weekly Chronicles – August ’25 Week III
The influence of sentiment analysis in enhancing early warning system model f...
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
OpenACC and Open Hackathons Monthly Highlights July 2025

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