我想实现带有必需参数和可选参数的导入功能,以这种方式运行:
python manage.py import --mode archive
其中 --mode
是必需的,archive
也是必需的。
我正在使用 argparse 库。
class Command(BaseCommand):
help = 'Import'
def add_arguments(self, parser):
parser.add_argument('--mode',
required=True,
)
parser.add_argument('archive',
required=True,
default=False,
help='Make import archive events'
)
但我收到错误:
TypeError: 'required' is an invalid argument for positionals
最佳答案
您创建了一个位置参数(名称前面没有 --
选项)。位置参数总是是必需的。您不能对此类选项使用 required=True
,只需删除 required
。也删除 default
;必需的参数不能有默认值(它永远不会被使用):
parser.add_argument('archive',
help='Make import archive events'
)
如果您想让 archive
成为命令行开关,请改用 --archive
。
关于python - 'required' 是 python 命令中位置参数的无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45078474/