Fix ir_tool argparse subcommand usage. (#14804)
The "cp" alias for "copy" was not working, instead producing an error:
`error: Unrecognized sub-command {args.sub_command}"`.
The docs (https://docs.python.org/3/library/argparse.html#sub-commands)
recommend using
```python
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(required=True)
parser_foo = subparsers.add_parser('foo')
parser_foo.set_defaults(func=foo)
# parse the args and call whatever function was selected
args = parser.parse_args(...)
args.func(args)
```
After switching to that style, "cp" and "copy" both work.
If an unknown subcommand is used, argparse has its own error message:
```bash
$ python -m iree.compiler.tools.ir_tool foo
usage: __main__.py [-h] {copy,cp,strip-data} ...
__main__.py: error: argument sub_command: invalid choice: 'foo' (choose from 'copy', 'cp', 'strip-data')
```
(and the program returns exit code `2`, not `0`)diff --git a/compiler/bindings/python/iree/compiler/tools/ir_tool/__main__.py b/compiler/bindings/python/iree/compiler/tools/ir_tool/__main__.py
index 6d52213..589b710 100644
--- a/compiler/bindings/python/iree/compiler/tools/ir_tool/__main__.py
+++ b/compiler/bindings/python/iree/compiler/tools/ir_tool/__main__.py
@@ -50,15 +50,18 @@
)
# copy (cp) command.
- cp_parser = subparsers.add_parser(
+ copy_parser = subparsers.add_parser(
"copy",
aliases=["cp"],
help="Read a file and then output it using the given options, without "
"modification",
)
- add_ouptut_options(cp_parser)
- cp_parser.add_argument("input_file", help="File to process")
- cp_parser.add_argument("-o", required=True, dest="output_file", help="Output file")
+ add_ouptut_options(copy_parser)
+ copy_parser.add_argument("input_file", help="File to process")
+ copy_parser.add_argument(
+ "-o", required=True, dest="output_file", help="Output file"
+ )
+ copy_parser.set_defaults(func=do_copy)
# strip-data command.
strip_data_parser = subparsers.add_parser(
@@ -77,19 +80,14 @@
strip_data_parser.add_argument(
"-o", required=True, dest="output_file", help="Output file"
)
+ strip_data_parser.set_defaults(func=do_strip_data)
args = parser.parse_args(argv)
return args
def main(args) -> int:
- if args.sub_command == "copy":
- return do_copy(args)
- if args.sub_command == "strip-data":
- return do_strip_data(args)
- else:
- print("error: Unrecognized sub-command {args.sub_command}", file=sys.stderr)
- return 1
+ args.func(args)
return 0