CLI Arguments with Environment Variables
You can also configure a CLI argument to read a value from an environment variable if it is not provided in the command line as a CLI argument.
To do that, use the envvar
parameter for typer.Argument()
:
import typer_cloup as typer
def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):
typer.echo(f"Hello Mr. {name}")
if __name__ == "__main__":
typer.run(main)
In this case, the CLI argument name
will have a default value of "World"
, but will also read any value passed to the environment variable AWESOME_NAME
if no value is provided in the command line:
Usage: main.py [OPTIONS] [NAME]
Arguments:
[NAME] [env var: AWESOME_NAME; default: World]
Options:
--help Show this message and exit.
π¬ Call it without a CLI argumentpython main.py
Hello Mr. World
π¬ Now pass a value for the CLI argumentpython main.py Czernobog
Hello Mr. Czernobog
π¬ And now use the environment variableAWESOME_NAME=Wednesday python main.py
Hello Mr. Wednesday
π¬ CLI arguments take precedence over env varsAWESOME_NAME=Wednesday p
Multiple environment variablesΒΆ
You are not restricted to a single environment variable, you can declare a list of environment variables that could be used to get a value if it was not passed in the command line:
import typer_cloup as typer
def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):
typer.echo(f"Hello Mr. {name}")
if __name__ == "__main__":
typer.run(main)
Check it:
Hide an env var from the help textΒΆ
By default, environment variables used will be shown in the help text, but you can disable them with show_envvar=False
:
import typer_cloup as typer
def main(name: str = typer.Argument("World", envvar="AWESOME_NAME", show_envvar=False)):
typer.echo(f"Hello Mr. {name}")
if __name__ == "__main__":
typer.run(main)
Check it:
Technical Details
In Click applications the env vars are hidden by default. π
In Typer these env vars are shown by default. π