解析器总是以列表的形式接收参数吗?

2024-10-03 09:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

Python版本:Python 3.5.1

Django版本:Django 1.10.2

我正在尝试编写自己的django自定义命令,我注意到要接受一个参数,它总是以列表的形式结束。你知道吗

https://docs.python.org/3/library/argparse.html

请注意,整数的参数是整数的列表。你知道吗

我想有一个参数,它接受以str格式编写的目录的相对路径或绝对路径。你知道吗

我的问题是:

  1. 甚至可以只接受参数作为解析器对象的单个str对象吗?你知道吗
  2. 如果可能的话,我需要改变什么?你知道吗

我现在的代码是

def add_arguments(self, parser):
    parser.add_argument('path', nargs='+', type=str)

    # Named (optional) arguments
    parser.add_argument(
        '--whiteware',
        action='store_true',
        dest='whiteware',
        default=True,
        help='Affects whiteware variants only',
    )

def handle(self, *args, **options):
    directory_in_str = options['path']

    print(directory_in_str)

Tags: path对象djangoself版本addparser列表
1条回答
网友
1楼 · 发布于 2024-10-03 09:17:45

您的问题在于创建命令行参数path的方式。你知道吗

从文件来看

nargs - The number of command-line arguments that should be consumed.

nargs='+'表示一个或多个空格分隔的参数,这些参数将由argparse转换到一个列表中。你知道吗

现在,如果需要字符串,可以执行以下操作:

parser.add_argument('path', type=str) #type is str by default, no need to specify this explicitly.

请注意,nargs在您想要限制选择类型等时非常有用

例如:

parser.add_argument('path', nargs='+', choices=['a', 'b', 'c'])

通过这种方式,您可以提供一系列选项,这些选项可以作为消费列表使用。你知道吗

甚至:

parser.add_argument('path', choices=['a', 'b', 'c'])

如果你想要一个单一的选项作为一个字符串。你知道吗

你可以在argparse options here in the documentation上阅读更多内容

相关问题 更多 >