Skip to content

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:

fast β†’πŸ’¬ Check the helppython main.py --help
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:

fast β†’python main.py --help
Usage: main.py [OPTIONS] [NAME]

Arguments:
[NAME] [env var: AWESOME_NAME, GOD_NAME; default: World]

Options:
--help Show this message and exit.

AWESOME_NAME=Wednesday python main.py
Hello Mr. Wednesday

GOD_NAME=Anubis python main.py
Hello Mr. Anubis

restart ↻

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:

fast β†’//Check the helppython main.py --help
Usage: main.py [OPTIONS] [NAME]

Arguments:
[NAME] [default: World]

Options:
--help Show this message and exit.

AWESOME_NAME=Wednesday python main.py
Hello Mr. Wednesday

restart ↻

Technical Details

In Click applications the env vars are hidden by default. πŸ™ˆ

In Typer these env vars are shown by default. πŸ‘€

You can ask questions about Typer. Try:
How can I terminate a program?
How to launch applications?
How to add help to CLI argument?