Python Click 库如何处理默认为标志和 True 的选项?
How does Python Click library handle options that are flags and True by default?
我刚刚偶然发现了一段代码,它定义了一个点击选项:
@click.option(
"-s",
"--status",
default=True,
is_flag=True,
help="Show status",
)
这是否意味着状态为True
,除非提供-s
,在这种情况下它将变为False
?
对于既是标志又默认为 True
的选项,在命令行中指定该选项会将该选项设置为 False
;未指定时将给出默认值 True
.
测试代码:
import click
@click.command()
@click.option(
"-s",
"--status",
default=True,
is_flag=True,
help="Show status",
)
def main(status):
click.echo('status: {}'.format(status))
if __name__ == "__main__":
commands = (
'',
'-s',
'--status',
'--help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for command in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + command)
time.sleep(0.1)
main(command.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
结果:
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
>
status: True
-----------
> -s
status: False
-----------
> --status
status: False
-----------
> --help
Usage: test.py [OPTIONS]
Options:
-s, --status Show status
--help Show this message and exit.
我刚刚偶然发现了一段代码,它定义了一个点击选项:
@click.option(
"-s",
"--status",
default=True,
is_flag=True,
help="Show status",
)
这是否意味着状态为True
,除非提供-s
,在这种情况下它将变为False
?
对于既是标志又默认为 True
的选项,在命令行中指定该选项会将该选项设置为 False
;未指定时将给出默认值 True
.
测试代码:
import click
@click.command()
@click.option(
"-s",
"--status",
default=True,
is_flag=True,
help="Show status",
)
def main(status):
click.echo('status: {}'.format(status))
if __name__ == "__main__":
commands = (
'',
'-s',
'--status',
'--help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for command in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + command)
time.sleep(0.1)
main(command.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
结果:
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
>
status: True
-----------
> -s
status: False
-----------
> --status
status: False
-----------
> --help
Usage: test.py [OPTIONS]
Options:
-s, --status Show status
--help Show this message and exit.