runtime
227 / 500
question 227 CLI & Automation · medium

Replace hand-written argument parsing

parse reads a report script's arguments by poking at the list by position. For good input it works, and those results must stay exactly the same. For bad input it crashes with IndexError or ValueError, or quietly ignores what it doesn't understand. Rewrite it with argparse so bad input stops with a usage error (SystemExit), as users of command-line tools expect.

Functionparse(argv)
Returns{'path': …, 'limit': …, 'verbose': …} exactly as now: limit an int defaulting to 10, verbose a flag
Must refuseno path, a limit that isn't a whole number, --limit with no value, and any option it doesn't know: all with SystemExit
Examples
callparse(['sales.csv', '--limit', '5'])returns{'path': 'sales.csv', 'limit': 5, 'verbose': False}
callparse(['sales.csv', '--verbose'])returns{'path': 'sales.csv', 'limit': 10, 'verbose': True}
callparse(['march.csv'])returns{'path': 'march.csv', 'limit': 10, 'verbose': False}
callparse([])raisesSystemExit
callparse(['sales.csv', '--limit', 'five'])raisesSystemExit

Loading your progress…

Replace hand-written argument parsing — Python practice · Runtime