[ python argparse ] makes it easy to write user-friendly command-line interfaces

Produces either the sum or the max

def main(args):
  args.accumulate(args.integers)
if __name__ == '__main__':
  ap = argparse.ArgumentParser(description='Process sum integer')
  ap.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
  ap.add_argument('integers', nargs='+', help='an integer for the accumulator')
  args = ap.parse_args()
  sys.exit(0 if main(args) else 1)

Usage

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

​store_const

stores the value specified by the const keyword argument.

Example 

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='test', action='store_const', const=42)
>>> parser.parse_args(['--foo'])

Namespace(test=42)

Options

nargs

ap.add_argument('one_arg', nargs=1, help='takes first parameter')
ap.add_argument('following_args', nargs='+', help='following parameters later')

if nargs = ‘+’, variable will be a list

>>> parser = argparse.ArgumentParser()
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args(['a', 'b'])
Namespace(foo=['a', 'b'])

Although nargs = 1, the foo will be list length 1 anyway.

>>> parser = argparse.ArgumentParser()
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs=1)
>>> parser.parse_args(['a'])
Namespace(foo=['a'])

name or flags

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')

type=int

>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

choices

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=('rock', 'paper', 'scissors'))
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

 

ref : https://docs.python.org/2/library/argparse.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s