A class that has configurable, typed attributes.
| 90 | |
| 91 | |
| 92 | class EnvironPrinter(Configurable): |
| 93 | """A class that has configurable, typed attributes.""" |
| 94 | |
| 95 | vars = List(trait=Unicode(), help="Environment variable").tag( |
| 96 | # NOTE: currently multiplicity is ignored by the traitlets CLI. |
| 97 | # Refer to issue GH#690 for discussion |
| 98 | config=True, |
| 99 | multiplicity="+", |
| 100 | argcompleter=EnvironCompleter, |
| 101 | ) |
| 102 | no_complete = Unicode().tag(config=True, argcompleter=SuppressCompleter) |
| 103 | style = Enum(values=["posix", "ndjson", "verbose"], default_value="posix").tag(config=True) |
| 104 | skip_if_missing = Bool(False, help="Skip variable if not set").tag(config=True) |
| 105 | |
| 106 | def print(self): |
| 107 | for env_var in self.vars: |
| 108 | if env_var not in os.environ: |
| 109 | if self.skip_if_missing: |
| 110 | continue |
| 111 | raise KeyError(f"Environment variable not set: {env_var}") |
| 112 | |
| 113 | value = os.environ[env_var] |
| 114 | if self.style == "posix": |
| 115 | print(f"{env_var}={value}") |
| 116 | elif self.style == "verbose": |
| 117 | print(f">> key: {env_var} value:\n{value}\n") |
| 118 | elif self.style == "ndjson": |
| 119 | JsonPrinter(parent=self).print({"key": env_var, "value": value}) |
| 120 | |
| 121 | |
| 122 | def bool_flag(trait, value=True): |