-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

1
  • 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 stackoverflow.com/questions/18700634/… Commented Sep 10, 2013 at 8:13

2 Answers 2

1
args, rest = parser.parse_known_args()
print args
print rest

rest should equal

['-cdl-sp', '-cdl-ck']
Sign up to request clarification or add additional context in comments.

Comments

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')

3 Comments

But it does not contain any value. python test_6.py -cdl sample -cdl-sp -cdl-ck
With "action='store_true'" parser doesn't expect any value. You will get a boolean value true if argument is there, false if not.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.