So I’m creating a CLI application using the Click package for Python. The CLI needs to grab some information about the system it is running on, and modify the prompts it presents to the user based on what it finds. For instance, it might want to know if the script is being ran on a Windows or Linux based OS.
To do this, I call a function to initialize some information about the system:
import platform
import click
environment_configuration = {}
environment_configuration["os"] = platform.system()
Now I set up the options for the CLI:
@click.command()
@click.option(
"--foo",
prompt="Enter the value for the foo command"
)
@click.pass_context
def run(ctx, foo):
print(f"Foo: ${foo}")
Now I want to change the prompt for the --foo
option based on the OS.
If we’re on Linux, I want the prompt to say
“Enter the value for the foo command. You can get this value by running
cat /etc/foo
in the terminal”
And if we’re on Windows, I want the prompt to say
“Enter the value for the foo command. You can get this value by running
Get-Content C:/ProgramData/foo
in Powershell”
The problem is that if I create another function to set the prompts, and I try and get the option by calling click.get_current_context().command.params["foo"]
, I get an error saying
There is no active click context.
I suppose I could set each prompt by creating a map like this:
prompt_map = [
"foo": "Enter the value for the foo command"
]
if environment_configuration["os"] == "Linux":
prompt_map["foo"] = "Enter the value for the foo command. You can get this value by running cat /etc/foo in the terminal"
elif environment_configuration["os"] == "Windows":
prompt_map["foo"] = "Enter the value for the foo command. You can get this value by running Get-Content C:/ProgramData/foo in Powershell"
@click.command()
@click.option(
"--foo",
prompt=prompt_map["foo"]
)
@click.pass_context
def run(ctx, foo):
print(f"Foo: ${foo}")
But this seems clunky. Does anyone know a better solution?