Python argparse:参数太少

Python argparse: Too few arguments

这是我的代码:

def parse_args():
    parser = argparse.ArgumentParser(description='Simple training script for object detection from a CSV file.')
    parser.add_argument('csv_path', help='Path to CSV file')
    parser.add_argument('--weights', help='Weights to use for initialization (defaults to ImageNet).', default='imagenet')
    parser.add_argument('--batch-size', help='Size of the batches.', default=1, type=int)

    return parser.parse_args()

当我 运行 我的代码时,我得到一个错误:

usage: Train.py [-h] [--weights WEIGHTS] [--batch-size BATCH_SIZE] csv_path
Train.py: error: too few arguments

知道我哪里出错了吗?

第一个参数 csv_path 是必需的(您没有提供一些默认值),因此您需要将其传递到命令行,如下所示:

python Train.py some_file.csv  # or the path to your file if it's not in the same directory

这是因为您没有指定 nargs 每个标志后预期的参数数量:

import argparse

def parse_args():
    parser = argparse.ArgumentParser(description='Simple training script for object detection from a CSV file.')
    parser.add_argument('csv_path', nargs="?", type=str, help='Path to CSV file')
    parser.add_argument('--weights', nargs="?", help='Weights to use for initialization (defaults to ImageNet).', default='imagenet')
    parser.add_argument('--batch-size', nargs="?", help='Size of the batches.', default=1, type=int)

    return parser.parse_args()
parse_args()

根据文档:

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:

详情here

试试这个:

import argparse
import sys
import csv

parser = argparse.ArgumentParser()
parser.add_argument('--file', default='fileName.csv')
args = parser.parse_args()
csvdata = open(args.file, 'rb')