简体   繁体   中英

Storing `nargs=3` as multiple variables

I want to be able to run both those commands:

python3 arguments.py --option1 reference
python3 arguments.py --option2 a b c

I have this code, which works:

import argparse


"""
" Parse arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('--option1', help="Do stuff with the one argument.")
parser.add_argument('--option2', nargs=3, help="Do stuff with all three arguments.")
  # https://docs.python.org/3/library/argparse.html#nargs
args = parser.parse_args()

if args.option1:
    print(args.option1) # will contain a string
if args.option2:
    print(len(args.option2), "arguments:")
    print(args.option2) # will contain a list
    print(args.option2[0])

But then I have to use args.option2[0] , args.option2[1] and args.option2[2] to access the values, which is poorly readable.

Using argparse, is there a way to do this?

  1. Store them as three separate variables. To access them, respectively, as argparse.audio , argparse.text , argparse.output variables?
  2. Document the order of those arguments in the code itself (so that they show in python3 arguments.py --help .)
  3. Check their values to make sure they are, respectively, a path to a file, a string and a path to a file.

Python unpacking:

a, b, c = args.option2

And for the help enhancement:

metavar=('a','b','c')

See the docs.

Check the types, file path, dir etc yourself after parsing. You don't get bonus points for doing everything in the parser. Filenames are just strings; it's what you (can) do with them that differs, such as open for reading (requires an existing file) versus open for writing (creates a new file).

You could even do

args.a, args.b, arg.c = args.option2

(if you need to pass the args namespace around, rather than 3 individual variables.) Once you have parsed the input, the rest is standard Python.

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