-1

I have utility which pass multiple argument alongwith require element Could anyone provide some input How can I handle this scenario using argparse. Please find the sample code

#! /usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-cdl", dest = "input_file")
args = parser.parse_args()
print args

Command Line :  python test_6.py -cdl sample (workfine)

utility also pass :  python test_6.py -cdl sample -cdl-sp -cdl-ck

The last two argument for tool.As my program I need to take sample file and ignore rest two argument without any error.In current code, it give me error

user765443
  • 1,856
  • 7
  • 31
  • 56
  • it should say "invalide choice: -cdl-sp" if you want to avoid this (which is not recommand) have a look at this one and may be you'll be able to test when an error occurs and fail silently http://stackoverflow.com/questions/18700634/python-argparse-integer-condition-12/18700996#18700996 –  Sep 10 '13 at 08:13

2 Answers2

1

You can just add options for the arguments you don't need.

parser.add_argument("-cdl-sp", dest = "sp",  action='store_true')
parser.add_argument("-cdl-sk", dest = "sk",  action='store_true')
MatthieuW
  • 2,292
  • 15
  • 25
  • But it does not contain any value. python test_6.py -cdl sample -cdl-sp -cdl-ck – user765443 Sep 10 '13 at 09:22
  • With "action='store_true'" parser doesn't expect any value. You will get a boolean value true if argument is there, false if not. – MatthieuW Sep 10 '13 at 09:39
  • it is also valid statement but above solution works better for me.As I write wrapper for call tool and some user can add more option and I need not to change any code But thanks for reply – user765443 Sep 11 '13 at 07:58
1
args, rest = parser.parse_known_args()
print args
print rest

rest should equal

['-cdl-sp', '-cdl-ck']
hpaulj
  • 221,503
  • 14
  • 230
  • 353