单击 Python 可重新启动清除所有参数的命令



我下面的脚本保存在"bike.py"中并注册为bikeshell 命令。我想运行一个简单的bike filter -c chicago -m 1 -d 1命令来探索chicago作为城市、1月和1作为星期几的数据。我使用prompt=True来捕获命令中未指定的任何选项。

我还希望能够在最后重新启动命令并清除所有现有参数,以便该命令将在重新启动时提示我进行citymonthday of week。但是,代码不能这样做。它只是运行脚本内部的内容并给我错误,因为如果没有传入的参数,脚本将无法运行。

我应该如何使用点击来执行此操作?

@click.group()
@click.pass_context
def main():
ctx.ensure_object(dict)

@main.command()
@click.option('-city', '-c', prompt=True)
@click.option('-month', '-m', prompt=True)
@click.option('-day_of_week', '-d', prompt=True)
@click.pass_context
def filter(ctx, city, month, day_of_week):
# load filtered data
...
# restart the program
if click.confirm('Restart to explore another dataset?') if not False:
import sys
sys.argv.clear()
ctx.invoke(filter)

您可以更改过滤器命令,以便手动执行提示。我不认为 Click 会知道否则提示,因为这不是一个常见的用例,也不符合no-magic点击风格指南。

@main.command()
@click.option('-city', '-c')
@click.option('-month', '-m')
@click.option('-day_of_week', '-d')
@click.pass_context
def filter(ctx, city, month, day_of_week):
# prompt if not passed in
if city is None:
city = click.prompt('City: ')
if month is None:
month = click.prompt('Month: ')
if day_of_week is None:
day_of_week = click.prompt('Day of the week: ')
# load filtered data
...
# restart the program
if click.confirm('Restart to explore another dataset?'):
ctx.invoke(filter)

或者,如果您真的想依赖内置功能,则可以通过覆盖Option类和提示功能来获得一些里程。

最新更新