简体   繁体   中英

How to make positional argument optional in argparser based on some condition in python

I want to write a python code in which, based on some arguments passed from command line I want to make positional argument optional.

For example, My python program is test.py, and with it I can give --init, --snap, --check options. Now if I have given --snap and --check option, then file name is compulsory ie test.py --snap file1

but if I have given --init option then it should not take any other arguments. ie in this case file name is optional: test.py --init

How to implement this condition

If you are ok with changing the command line you are passing a little bit, then a set of subparsers should work.

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')

init_parser = subparsers.add_parser('init', help='do the init stuff')

snap_parser = subparsers.add_parser('snap', help='do the snap stuff')
snap_parser.add_argument('--file', '-f', required=True)

check_parser = subparsers.add_parser('check', help='do the check stuff')
check_parser.add_argument('--file', '-f', required=True)

args = parser.parse_args()

print args

And then the output...

> python foobar.py init
Namespace()

> python foobar.py check
usage: foobar.py check [-h] --file FILE
foobar.py check: error: argument --file/-f is required

> python foobar.py check --file foobar.txt
Namespace(file='foobar.txt')

General help:

> python foobar.py --help
usage: foobar.py [-h] {init,snap,check} ...

positional arguments:
  {init,snap,check}  sub-command help
    init             do the init stuff
    snap             do the snap stuff
    check            do the check stuff

optional arguments:
  -h, --help         show this help message and exit

And specific sub-command help

> python foobar.py snap -h
usage: foobar.py snap [-h] --file FILE

optional arguments:
  -h, --help            show this help message and exit
  --file FILE, -f FILE

Your other option is to use nargs as @1.618 has already mentioned.

argparse allows you to specify that certain args have their own args, like so:

parser.add_argument("--snap", nargs=1) or use a + to allow for an arbitrary number of "subargs"

After you call parse_args() , the values will be in a list: filename = args.snap[0]

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