Python taking arguments from command line with argparse

Post date: Apr 16, 2016 8:11:41 PM

Use package argparse this is how the code looks like

import argparse parser = argparse.ArgumentParser() parser.add_argument("--day_a", required = True) parser.add_argument("--day_b", required = True) parser.add_argument("--date_list", required = False) parser.add_argument("--num_total", required = False) parser.add_argument("--avg_price", required = False) args = parser.parse_args() print ''' day_a: {day_a} day_b: {day_b} date_list: {date_list} num_total: {num_total} avg_price: {avg_price} '''.format(day_a=args.day_a , day_b=args.day_b , date_list=args.date_list , num_total=args.num_total , avg_price=args.avg_price)

Here are example

$ python test_argparse.py --day_a '2016-03-21' --day_b 2016-03-14 --date_list ['2016-01-01','2016-05-02'] --num_total 23 --avg_price 12.34 day_a: 2016-03-21 day_b: 2016-03-14 date_list: [2016-01-01,2016-05-02] num_total: 23 avg_price: 12.34 $ python test_argparse.py --day_a '2016-03-21' --day_b 2016-03-14 --date_list ['2016-01-01', '2016-05-02'] --num_total 23 --avg_price 12.34 usage: test_argparse.py [-h] --day_a DAY_A --day_b DAY_B [--date_list DATE_LIST] [--num_total NUM_TOTAL] [--avg_price AVG_PRICE] test_argparse.py: error: unrecognized arguments: 2016-05-02] # The error message is caused by the space " " in "['2016-01-01', '2016-05-02']". The command argparse separates each argument by space, so it interprets 2016-05-02 as another argument. $ python test_argparse.py --day_a '2016-03-21' --day_b 2016-03-14 --date_list ['2016-01-01'\, '2016-05-02'] --num_total 23 --avg_price 12.34 usage: test_argparse.py [-h] --day_a DAY_A --day_b DAY_B [--date_list DATE_LIST] [--num_total NUM_TOTAL] [--avg_price AVG_PRICE] test_argparse.py: error: unrecognized arguments: 2016-05-02] $ python test_argparse.py --day_a '2016-03-21' --day_b 2016-03-14 --date_list "['2016-01-01', '2016-05-02']" --num_total 23 --avg_price 12.34 day_a: 2016-03-21 day_b: 2016-03-14 date_list: ['2016-01-01', '2016-05-02'] num_total: 23 avg_price: 12.34 $ python test_argparse.py --day_a '2016-03-21' --day_b 2016-03-14 --date_list "['2016-01-01', '2016-05-02']" --num_total 23 day_a: 2016-03-21 day_b: 2016-03-14 date_list: ['2016-01-01', '2016-05-02'] num_total: 23 avg_price: None $ python test_argparse.py --day_a '2016-03-21' --date_list "['2016-01-01', '2016-05-02']" --num_total 23 usage: test_argparse.py [-h] --day_a DAY_A --day_b DAY_B [--date_list DATE_LIST] [--num_total NUM_TOTAL] [--avg_price AVG_PRICE] test_argparse.py: error: argument --day_b is required $ python test_argparse.py --day_a "'2016-03-21'" --day_b "2016-03-14" day_a: '2016-03-21' day_b: 2016-03-14 date_list: None num_total: None avg_price: None