简体   繁体   中英

argparse to validated unknown args in python

test1.py:

_argParserObj = argparse.ArgumentParser()
_argParserObj.add_argument('--tool', type=str, dest='tool')
parsedArgs, passthroughs = _argParserObj.parse_known_args()

When test1.py is executed as below

test1.py --tool abc arg1 arg2 --invalid_switch

I would like to show the below error. But still accept arg1 and arg2 as extra arguments

test1.py: error: unrecognized arguments: -invalid_switch

Currently it just parses invalid_switch also a passthrough and throw any error.

Can anyone please suggest how to achieve this?

You can try parse_args() instead of parse_known_args()

_argParserObj = argparse.ArgumentParser()
_argParserObj.add_argument('--tool', type=str, dest='tool')
parsedArgs, passthroughs = _argParserObj.parse_args()

parse_args() will show this error in your case

test.py: error: unrecognized arguments: --invalid_switch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM