选项¶
向命令添加选项可以使用{func}' select '来完成。在运行时,装饰器调用{类}'选项'类。Click中的选项与{ref}“位置参数”不同
有用且经常使用的kwargs有:
default:传递默认值。help:设置帮助消息。nargs:设置参数的数量。required:需要选项。type: Sets parameter type
期权装饰者¶
Click希望您将至少两个位置参数传递给选项装饰器。它们是选项名称和函数参数名称。
@click.command()
@click.option('--string-to-echo', 'string_to_echo')
def echo(string_to_echo):
click.echo(string_to_echo)
$ echo --help
Usage: echo [OPTIONS]
Options:
--string-to-echo TEXT
--help Show this message and exit.
然而,如果您不传递函数参数名称,那么Click将尝试推断它。命名选项的一种简单方法是采用函数参数,在前面添加两个破折号,然后将虚线转换为破折号。在这种情况下,Click将正确推断函数参数名称,以便您只能添加选项名称。
@click.command()
@click.option('--string-to-echo')
def echo(string_to_echo):
click.echo(string_to_echo)
$ echo --string-to-echo 'Hi!'
Hi!
更正式地,Click将尝试通过以下方式推断函数参数名称:
如果位置参数名称没有前置,则会选择它。
如果位置参数名称以两个破折号开头,则选择给出的第一个破折号。
否则选择以一个破折号为开头的第一个位置参数。
选择的位置参数转换为大写字母,从开头删除最多两个破折号,其他破折号转换为虚线以获取函数参数名称。
装饰器参数 |
函数名 |
|---|---|
|
foo_bar |
|
X |
|
dest |
|
CamelCase |
|
F |
|
F |
|
_f |
基本示例¶
A simple click.Option takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is str.
@click.command()
@click.option('--text')
def print_this(text):
click.echo(text)
$ print-this --text=this
this
$ print-this
$ print-this --help
Usage: print-this [OPTIONS]
Options:
--text TEXT
--help Show this message and exit.
设置默认¶
而不是设置 type ,您可以设置默认值,Click将尝试推断类型。
@click.command()
@click.option('--n', default=1)
def dots(n):
click.echo('.' * n)
$ dots --help
Usage: dots [OPTIONS]
Options:
--n INTEGER
--help Show this message and exit.
多值选项¶
要使选项采用多个值,请传递 nargs .请注意,仅支持固定数量的参数。这些值作为数组传递给基础函数。
@click.command()
@click.option('--pos', nargs=2, type=float)
def findme(pos):
a, b = pos
click.echo(f"{a} / {b}")
$ findme --pos 2.0 3.0
2.0 / 3.0
作为二元组的多值选项¶
:{版本添加} 4.0:
正如你所看到的,通过使用 nargs 设置为一个特定的数字,结果元组中的每个项目都是相同的类型。这可能不是你想要的。通常,您可能希望为元组中的不同索引使用不同的类型。为此,您可以直接指定一个tuple作为type:
@click.command()
@click.option('--item', type=(str, int))
def putitem(item):
name, id = item
click.echo(f"name={name} id={id}")
在命令行上:
$ putitem --item peter 1338
name=peter id=1338
By using a tuple literal as type, nargs gets automatically set to the
length of the tuple and the click.Tuple type is automatically
used. The above example is thus equivalent to this:
@click.command()
@click.option('--item', nargs=2, type=click.Tuple([str, int]))
def putitem(item):
name, id = item
click.echo(f"name={name} id={id}")
多种选择方案¶
多选项格式允许您使用一个命令行条目多次调用基础函数。如果设置,默认值必须是列表或tuple。将字符串设置为默认值将被解释为字符列表。
@click.command()
@click.option('--message', '-m', multiple=True)
def commit(message):
click.echo('\n'.join(message))
$ commit -m foo -m bar -m here
foo
bar
here
计数¶
要计算期权传递的发生率 count=True .如果未传递该选项,则计数为0。计数通常用于冗长。
@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
click.echo(f"Verbosity: {verbose}")
$ log
Verbosity: 0
$ log -vvv
Verbosity: 3
布尔¶
布尔选项(布尔标志)采用True或False值。最简单的情况将默认值设置为 False 如果旗帜未通过,并且 True 如果是的话
import sys
@click.command()
@click.option('--shout', is_flag=True)
def info(shout):
rv = sys.platform
if shout:
rv = rv.upper() + '!!!!111'
click.echo(rv)
$ info
linux
$ info --shout
LINUX!!!!111
要更明确地实现这一点,请传递on-选项 / 关闭选项。点击将自动设置 is_flag=True . Click始终希望您提供启用和禁用标志,以便您稍后可以更改默认值。
import sys
@click.command()
@click.option('--shout/--no-shout', default=False)
def info(shout):
rv = sys.platform
if shout:
rv = rv.upper() + '!!!!111'
click.echo(rv)
$ info
linux
$ info --shout
LINUX!!!!111
$ info --no-shout
linux
如果正斜线 (/ )已经包含在您的选项名称中,您可以使用 ; .在Windows中 / 通常用作前置字符。
@click.command()
@click.option('/debug;/no-debug')
def log(debug):
click.echo(f"debug={debug}")
:{versionchanged} 6.0:
如果您只想为第二个选项定义别名,那么您将需要使用前置空白来消除格式字符串的歧义。
import sys
@click.command()
@click.option('--shout/--no-shout', ' /-N', default=False)
def info(shout):
rv = sys.platform
if shout:
rv = rv.upper() + '!!!!111'
click.echo(rv)
$ info --help
Usage: info [OPTIONS]
Options:
--shout / -N, --no-shout
--help Show this message and exit.
标志值¶
要让标志将值传递到基础函数集 flag_value .这会自动设置 is_flag=True .要设置默认标志,请设置 default=True .设置标志值可用于创建这样的模式:
import sys
@click.command()
@click.option('--upper', 'transformation', flag_value='upper', default=True)
@click.option('--lower', 'transformation', flag_value='lower')
def info(transformation):
click.echo(getattr(sys.platform, transformation)())
$ info --help
Usage: info [OPTIONS]
Options:
--upper
--lower
--help Show this message and exit.
$ info --upper
LINUX
$ info --lower
linux
$ info
LINUX
来自环境变量的值¶
要从特定环境变量传入值,请使用 envvar .
@click.command()
@click.option('--username', envvar='USERNAME')
def greet(username):
click.echo(f"Hello {username}!")
$ export USERNAME=john
$ greet
Hello john!
如果将列表传递给 envvar ,选择找到的第一个环境变量。
@click.command()
@click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])
def greet(username):
click.echo(f"Hello {username}!")
$ export ALT_USERNAME=Bill
$ export USERNAME=john
$ greet
Hello Bill!
环境价值观的多种选择¶
As options can accept multiple values, pulling in such values from
environment variables (which are strings) is a bit more complex. The way
Click solves this is by leaving it up to the type to customize this
behavior. For both multiple and nargs with values other than
1, Click will invoke the ParamType.split_envvar_value() method to
perform the splitting.
The default implementation for all types is to split on whitespace. The
exceptions to this rule are the File and Path types
which both split according to the operating system's path splitting rules.
On Unix systems like Linux and OS X, the splitting happens on
every colon (:), and for Windows, splitting on every semicolon (;).
@click.command()
@click.option('paths', '--path', envvar='PATHS', multiple=True,
type=click.Path())
def perform(paths):
for path in paths:
click.echo(path)
if __name__ == '__main__':
perform()
$ export PATHS=./foo/bar:./test
$ perform
./foo/bar
./test
其他前缀字符¶
点击除了可以处理前置字符 - 用于选择。点击可以使用 / , + 以及其他人。请注意,在POSIX中,替代前缀字符通常使用得非常少。
@click.command()
@click.option('+w/-w')
def chmod(w):
click.echo(f"writable={w}")
$ chmod +w
writable=True
$ chmod -w
writable=False
There are special considerations for using / as prefix character, see 布尔 for more.
可选值¶
向选项提供值可以成为可选的,在这种情况下,仅提供选项的标记而不提供值将显示提示或使用其 flag_value .
设置 is_flag=False, flag_value=value 告诉Click该选项仍然可以传递一个值,但前提是该标志被赋予 flag_value .
@click.command()
@click.option("--name", is_flag=False, flag_value="Flag", default="Default")
def hello(name):
click.echo(f"Hello, {name}!")
$ hello
Hello, Default!
$ hello --name Value
Hello, Value!
$ hello --name
Hello, Flag!