Skip to content

Commit

Permalink
Allow subcommand_cli_from_dict to specify console_outputs (#175)
Browse files Browse the repository at this point in the history
* Add console_outputs option to subcommand_cli_from_dict

* Add console_outputs test for cli_from_dict.

* Fix formatting.
  • Loading branch information
mirceamironenco authored Oct 11, 2024
1 parent a867851 commit 34f3b14
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/tyro/extras/_subcommand_cli_from_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ def subcommand_cli_from_dict(
description: Optional[str] = None,
args: Optional[Sequence[str]] = None,
use_underscores: bool = False,
console_outputs: bool = True,
) -> T: ...


Expand All @@ -29,6 +30,7 @@ def subcommand_cli_from_dict(
description: Optional[str] = None,
args: Optional[Sequence[str]] = None,
use_underscores: bool = False,
console_outputs: bool = True,
) -> Any: ...


Expand All @@ -39,6 +41,7 @@ def subcommand_cli_from_dict(
description: Optional[str] = None,
args: Optional[Sequence[str]] = None,
use_underscores: bool = False,
console_outputs: bool = True,
) -> Any:
"""Generate a subcommand CLI from a dictionary of functions.
Expand Down Expand Up @@ -86,6 +89,10 @@ def subcommand_cli_from_dict(
This primarily impacts helptext; underscores and hyphens are treated equivalently
when parsing happens. We default helptext to hyphens to follow the GNU style guide.
https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
console_outputs: If set to `False`, parsing errors and help messages will be
supressed. This can be useful for distributed settings, where `tyro.cli()`
is called from multiple workers but we only want console outputs from the
main one.
"""
# We need to form a union type, which requires at least two elements.
assert len(subcommands) >= 2, "At least two subcommands are required."
Expand All @@ -108,4 +115,5 @@ def subcommand_cli_from_dict(
description=description,
args=args,
use_underscores=use_underscores,
console_outputs=console_outputs
)
19 changes: 19 additions & 0 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,25 @@ class Class:
assert error == ""


def test_suppress_console_outputs_fromdict() -> None:
def foo(track: bool) -> None:
print(track)

def bar(track: bool) -> None:
print(track)

target = io.StringIO()
with pytest.raises(SystemExit), contextlib.redirect_stderr(target):
tyro.extras.subcommand_cli_from_dict(
{"foo": foo, "bar": bar},
args="foo --reward.trac".split(" "),
console_outputs=False,
)

error = target.getvalue()
assert error == ""


def test_similar_arguments_subcommands() -> None:
@dataclasses.dataclass
class RewardConfig:
Expand Down

0 comments on commit 34f3b14

Please sign in to comment.