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