Python argparse:参数太少了

时间:2018-01-30 13:46:24

标签: python pycharm argparse

这是我的代码:

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

知道我哪里出错了吗?

3 个答案:

答案 0 :(得分:1)

第一个arg csv_path是必需的(你没有提供一些默认值),所以你需要将它传递给你的命令行,如下所示:

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

答案 1 :(得分:0)

这是因为您没有在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

答案 2 :(得分:0)

尝试一下:

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')