TypeError: ‘required’ is an invalid argument for positionals 的解决方法

当我在使用argparse模块时,遇到了如下错误:

import argparse

parser = argparse.ArgumentParser(description = 'debug_example')
parser.add_argument ('--data_root', default = 'data/path', type = str, required=False, help = 'the dataset path')
parser.add_argument ('result_root', default = 'result/path', type = str, required=False, help = 'the output path')
args = parser.parse_args()

print(args.data_root)
print(args.result_root)

TypeError: 'required' is an invalid argument for positionals

解决方案

在’result_root’前面加上- -;

parser.add_argument ('--result_root', default = 'result/path', type = str, required=True, help = 'the output path')

原因

required = False 只能用于可选参数。 对于可选参数,应该使用 - -,如果没有 - -,python 会将其视为位置参数。 因此 add_argument 函数里的参数required参数对位置参数 ‘result_root’ 无效。

解决错误后:

import argparse

parser = argparse.ArgumentParser(description = 'debug_example')
parser.add_argument ('--data_root', default = 'data/path', type = str, required=False, help = 'the dataset path')
parser.add_argument ('--result_root', default = 'result/path', type = str, required=False, help = 'the output path')
args = parser.parse_args()

print(args.data_root)
print(args.result_root)

运行结果:

data/path
result/path
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐