Python版本:Python 3.5.1
Django版本:Django 1.10.2
我正在尝试编写自己的django自定义命令,我注意到要接受一个参数,它总是以列表的形式结束。你知道吗
见https://docs.python.org/3/library/argparse.html
请注意,整数的参数是整数的列表。你知道吗
我想有一个参数,它接受以str格式编写的目录的相对路径或绝对路径。你知道吗
我的问题是:
我现在的代码是
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)
您的问题在于创建命令行参数
path
的方式。你知道吗从文件来看
和
nargs='+'
表示一个或多个空格分隔的参数,这些参数将由argparse
转换到一个列表中。你知道吗现在,如果需要字符串,可以执行以下操作:
请注意,
nargs
在您想要限制选择类型等时非常有用例如:
通过这种方式,您可以提供一系列选项,这些选项可以作为消费列表使用。你知道吗
甚至:
如果你想要一个单一的选项作为一个字符串。你知道吗
你可以在argparse options here in the documentation上阅读更多内容
相关问题 更多 >
编程相关推荐