perrigoh / image_classifier_pytorch_udacity

Image classifier model using PyTorch
MIT License
0 stars 0 forks source link

rework argparser #7

Closed perrigoh closed 1 year ago

perrigoh commented 1 year ago

to run train.py and predict.py using command lines with/without flags and arguments, reference quoted from stackoverflow:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()

print(args) % test.py Namespace(example=None) % test.py --example Namespace(example=1) % test.py --example 2 Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with
    parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

    then
    % test.py Namespace(example=1)

Thank you, stackoverflow and its contributors!


details of add_argument() method, reference quoted from python argparse:
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.

action - The basic type of action to be taken when this argument is encountered at the command line.

nargs - The number of command-line arguments that should be consumed.

const - A constant value required by some action and nargs selections.

default - The value produced if the argument is absent from the command line and if it is absent from the namespace object.

type - The type to which the command-line argument should be converted.

choices - A container of the allowable values for the argument.

required - Whether or not the command-line option may be omitted (optionals only).

help - A brief description of what the argument does.

metavar - A name for the argument in usage messages.

dest - The name of the attribute to be added to the object returned by parse_args().

Thank you, python and its contributors!