parser
Mojo module 🡭
parser
A very basic CLI Opt Parser.
from testing import assert_equal, assert_true
from extramojo.cli.parser import OptParser, OptConfig, OptKind
var args = List(String("--file"), String("/path/to/thing"), String("--count"), String("42"), String("--fraction"), String("-0.2"), String("--verbose"), String("ExtraFile.tsv"))
var program_name = "example"
var parser = OptParser(name="example", description="An example program.")
parser.add_opt(OptConfig("file", OptKind.StringLike, default_value=None, description="A file with something in it."))
parser.add_opt(OptConfig("count", OptKind.IntLike, default_value=String("100"), description="A number."))
parser.add_opt(OptConfig("fraction", OptKind.FloatLike, default_value=String("0.5"), description="Some interesting fraction to keep."))
# Note that with flags, the OptKind must be BoolLike and there must be a default_value specified.
parser.add_opt(OptConfig("verbose", OptKind.BoolLike, is_flag=True, default_value=String("False"), description="Turn up the logging."))
# Specify any needed arguments. If at least n arguments aren't found after parsing the opts, an exception will be raised.
parser.expect_at_least_n_args(1, "Additional files to process")
# Note, a user would call parser.parse_sys_args()
var opts = parser.parse_args(args)
assert_equal(opts.get_string("file"), String("/path/to/thing"))
assert_equal(opts.get_int("count"), 42)
assert_equal(opts.get_float("fraction"), -0.2)
assert_equal(opts.get_bool("verbose"), True)
assert_true(len(opts.get_help_message()[]) > 0)
Structs
OptKind
: The viable types for an option to have.OptValue
: When an option is parsed, it’s stored as an OptValue.OptConfig
: Create an option to be added to theOptParser
.ParsedOpts
: The parsed CLI options. Access your values withParsedOpts.get_string()
,ParsedOpts.get_int()
, etc.OptParser
: [OptParser
] will try to parse your long-form CLI options.Subcommand
: A subcommand.SubcommandParser
: Subcommands are created by passing in the command, and anOptParser
.