点击包:命令选项动态提示信息

问题描述 投票:0回答:1

我正在使用 Python 包 Click 为我的代码编写用户界面。基本上,我想定义一个

command
,其中包含在代码运行期间定义的提示消息,取决于运行的先前步骤,而不是始终固定为相同的字符串。

我知道我可以将提示消息定义为:

@click.command()
@click.option('--r', prompt='fixed message, always the same')
def scale_r(r):
    return 10 * float(r)

if __name__ == '__main__':
    scale_r()

所以,我想要在代码执行过程中定义提示消息,然后在执行命令时使用它

scale_r
:

if __name__ == '__main__':
   prompt_msg = ... 
   scale_r()  # using prompt_msg as text to be printed to the user

我应该如何更改命令的定义

scale_r
?我应该如何“传递”
prompt_msg
给它?

谢谢您的帮助!

然后,将根据代码的特定运行向用户提示一条消息。也就是说,他/她不会收到固定消息的提示。

python user-interface python-click
1个回答
0
投票

命令的执行是独立的,默认情况下,运行之间不保存状态。如果你想处理一些动态消息,它应该保存在某个地方。以最后一次执行时间为例,这种方式是通过配置文件来完成的。

from datetime import datetime
import os

import click
from platformdirs import user_config_path

conf_file = user_config_path() / "scale_r.conf"
if not conf_file.exists():
    conf_file.touch()

def get_prompt_msg() -> str:
    last_execution = conf_file.read_text()
    prompt_msg = "Input a float"
    if last_execution:
        prompt_msg += f" (last execution was at {last_execution})"
    return prompt_msg

@click.command()
@click.option("--r", prompt=get_prompt_msg(), type=float)
def scale_r(r):
    print(10 * r)

if __name__ == "__main__":
    conf_file.write_text(datetime.now().isoformat())
    scale_r()
© www.soinside.com 2019 - 2024. All rights reserved.