python - 'required' 是 python 命令中位置参数的无效参数

标签 python import arguments argparse

我想实现带有必需参数和可选参数的导入功能,以这种方式运行:

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/

相关文章:

python - 类型错误 : can't multiply sequence by non-int of type 'float' even if already parsed with float()

python - MatLab 与 Python - 向量化和 reshape 数组

java - 如何更改 java.sql.Connection con;进口申报和连接con;

java - 将类的变量导入到另一个类

python - 在 Python 2.6 中,如何将列表对象传递给需要参数列表的方法?

python - 线宽 Manim

C# 等效于 Python 的 urlsafe_b64encode

python - 导入错误 : No module named package

JavaScript:属性描述符在传递给函数时被忽略

java - 类中可变数量的参数