0
def getOptions():
    parser = argparse.ArgumentParser(description='Parses Command.')
    parser.add_argument('-t','--train',nargs='+',help='Training data directories.')
    parser.add_argument('-i','--iteration',type=int,nargs='+',help='Number of iteration.')
    options = parser.parse_args()
    return options

I know that parser.parse_args() returns an not iterable object

i want to use "options.train" in a for loop but i cant go over that error. Also, vars dont work for me

  • So what exactly is your question about this? – mkrieger1 Dec 10 '22 at 14:38
  • Show the script call (with commandline arguments), `options` and how you are trying to use it. From the short question it's hard to tell where you are getting the error. – hpaulj Dec 10 '22 at 14:57
  • If you don't provide a `--train` argument, `options.train` will be `None`. You add a `default=[]` to the setup, so the default is iterable. During debugging it's a good idea to include a `print(options)` line. – hpaulj Dec 10 '22 at 15:58

1 Answers1

0

The reason you are encountering this error is that, you need to provide train arguments to parse_args() method either like following or providing it in command line:

import argparse


def get_options():
    parser = argparse.ArgumentParser(description='Parses Command.')
    parser.add_argument('-t', '--train', nargs='+', help='Training data directories.')
    parser.add_argument('-i', '--iteration', type=int, nargs='+', help='Number of iteration.')
    options = parser.parse_args(['-t', 'train1', 'train2'])
    return options


options = get_options()
print('train arguments:', options.train)

for option in options.train:
    print('train:', option)

Result of above code is the following:

train arguments: ['train1', 'train2']
train: train1
train: train2

Assuming the above Python code is saved into a file called train.py, it can be run at the command line without specifying arguments to parse_args() method:

$ python train.py -t train/etc train/etc2
train arguments: ['train/etc', 'train/etc2']
train: train/etc
train: train/etc2

In case there is no -t args to parse there is a possible way to handle occurred exception in try-except code block or refer to Python argparse: Make at least one argument required for more solutions of ensuring availability of inputs.

hamed.k
  • 23
  • 4