参数

论点是:

  • 本质上是位置性的。

  • 类似于有限版本的 options 可以接受任意数量的输入

  • Documented manually .

有用且经常使用的kwargs有:

  • default :传递默认值。

  • nargs :设置参数的数量。设置为-1以取任意数。

基本论点

最小 click.Argument 仅接受一个字符串参数:参数的名称。这将假设参数是必需的,没有默认值,并且类型为 str .

例子:

@click.command()
@click.argument('filename')
def touch(filename: str):
    """Print FILENAME."""
    click.echo(filename)

从命令行:

$ touch foo.txt
foo.txt

参数可以被分配为 parameter type .如果未提供类型,则使用默认值的类型。如果未提供默认值,则假定类型为 STRING .

关于所需论据的注释

可以通过设置提出所需的论点 required=True . 不建议这样做,因为我们认为命令行工具应该优雅地降级为没有操作。 我们这样认为是因为命令行工具经常使用收件箱输入来调用,并且如果收件箱为空,它们不应该出错。

多个参数

要设置参数数,请使用 nargs 夸格。它可以设置为任何正整和-1。将其设置为-1会使参数的数量任意(称为可变变量)并且只能使用一次。然后将参数打包为一个数组并传递给函数。

@click.command()
@click.argument('src', nargs=1)
@click.argument('dsts', nargs=-1)
def copy(src: str, dsts: tuple[str, ...]):
    """Move file SRC to DST."""
    for destination in dsts:
        click.echo(f"Copy {src} to folder {destination}")

从命令行:

$ copy foo.txt usr/david/foo.txt usr/mitsuko/foo.txt
Copy foo.txt to folder usr/david/foo.txt
Copy foo.txt to folder usr/mitsuko/foo.txt

关于处理文件的注意事项

这不是处理文件和文件路径的方式。这只是用作一个简单的例子。看到 处理文件 了解有关如何处理参数中的文件的更多信息。

参数逃逸序列

如果您想处理看起来像选项的参数,例如名为 -foo.txt--foo.txt ,您必须通过 -- 先分离器。通过后 -- ,您只能通过论点。这是BOX命令行工具的常见功能。

示例用法:

@click.command()
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
    """Print all FILES file names."""
    for filename in files:
        click.echo(filename)

从命令行:

$ touch -- -foo.txt bar.txt
-foo.txt
bar.txt

如果你不喜欢 -- marker,您可以将ignore_unknown_options设置为true以避免检查未知选项:

@click.command(context_settings={"ignore_unknown_options": True})
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
    """Print all FILES file names."""
    for filename in files:
        click.echo(filename)

从命令行:

$ touch -foo.txt bar.txt
-foo.txt
bar.txt

环境变量

参数可以使用环境变量。为此,请通过传递环境变量的名称 envvarclick.argument .

检查一个环境变量:

@click.command()
@click.argument('src', envvar='SRC', type=click.File('r'))
def echo(src):
    """Print value of SRC environment variable."""
    click.echo(src.read())

从命令行:

$ export SRC=hello.txt
$ echo
Hello World!

检查多个环境变量:

@click.command()
@click.argument('src', envvar=['SRC', 'SRC_2'], type=click.File('r'))
def echo(src):
    """Print value of SRC environment variable."""
    click.echo(src.read())

从命令行:

$ export SRC_2=hello.txt
$ echo
Hello World from second variable!