What this is about
A command-line program is one you start by typing its name and some extra words. Those extra words are options. ls -l has one option. git commit -m "note" has a subcommand, commit, and a flag with a value, -m.
This article shows how to read options in Mojo with our mojo-args library. It copies Python's argparse, so if you have used that, almost everything here will feel familiar.
Why it matters
Options turn a one-purpose script into a tool. Without them you edit the file each time you want a new input. With them, another person, or another program, can drive your tool with no edits.
Parsing options by hand is a classic source of bugs. What if the user writes --times=3 instead of --times 3? What if they type -q and -v together as -qv? A parser library handles all of that, and gives clear errors when the input makes no sense.
How it works
This is a complete program. We ran it on Mojo 1.2.0.
from args import ArgumentParser
def main() raises:
var p = ArgumentParser("greet")
p.add_argument("name")
p.add_argument("--times", type="int", default="1")
p.add_argument("-q", "--quiet", action="store_true")
var ns = p.parse_args(["ada", "--times", "3", "-q"])
print(ns.get_str("name"), ns.get_int("times"), ns.get_bool("quiet"))
It printed ada 3 True. Calling parse_args(["bo"]) printed bo 1 False.
Here is what each line does.
ArgumentParser("greet")makes a parser. The text is the program's name, used in messages.add_argument("name")adds a required word, which we call a positional argument.add_argument("--times", type="int", default="1")adds an option with a value. It must be a whole number. It defaults to 1.add_argument("-q", "--quiet", action="store_true")adds a flag. If you give it, the value is true. If you do not, it is false.parse_args(...)reads a list of words. To read the real command line, callparse_args()with no list.get_str,get_intandget_booltake values out of the result. You pick the type you want.
Subcommands
Tools such as git have subcommands. The README shows how to build one, with a parser modeled on our own GPU job runner:
var p = ArgumentParser("gpu-wait")
p.add_subparsers("command")
var run = p.add_parser("run")
run[].add_argument("--priority", type="int", default="0")
run[].add_argument("-q", "--quiet", action="store_true")
run[].add_argument("cmd", nargs="...")
The nargs="..." part means "take everything that is left", so the rest of the line is passed as a command. As in argparse, a short prefix is enough when it is not ambiguous: --prio 90 works for --priority. If the prefix could match two options, you get an error like ambiguous option: --p could match --priority, --preemptible.
Reading the real command line
The programs above give parse_args a list that we typed in. That is handy for tests. In a real tool, call parse_args() with no list, and the library reads the words the user typed. Build the program as a binary, then run it as ./greet ada --times 3 -q.
The library also accepts the styles people already know from argparse:
--times=3works the same as--times 3.-n5works as-n 5for a short option.- Bundled flags, such as
-qv, set two flags at once. - A bare
--ends the options, so what comes after it is not read as an option.
That last rule matters when your tool runs another command. gpu-wait run --prio 90 -- python train.py gives a priority of 90, and the words after -- are the command to run. The README shows this exact line.
What an error looks like
When we passed --times x, the program stopped with:
Unhandled exception caught during execution: argument --times: invalid int value: 'x'
The sentence argument --times: invalid int value: 'x' is the one argparse prints. We built the library to match those texts, so scripts that depend on them keep working.
How fast is it
The README ran a gpu-wait style parser with four subcommands through 200,000 parses of five valid command lines. Three runs each.
| build the parser | 200,000 parses | peak memory | |
|---|---|---|---|
Python argparse |
11.3 to 11.5 ms | 3,346 to 3,367 ms | 15.1 to 15.3 MB |
| mojo-args | 0.04 to 0.05 ms | 252 to 259 ms | 12.0 to 12.3 MB |
An empty Mojo program uses 11.4 MB, so the library adds under 1 MB. Does speed matter for a tool that parses once? A little, at start-up. It matters most for tools that other programs start many times a second.
What it does not do
- The
--helppage is a simple usage line and an option list. It does not use argparse's layout, and it is not part of our checks. - A usage error prints the top-level usage, even for a subcommand error. argparse prints the subcommand's.
- It does not support
count,store_const, mutually exclusive groups or@filearguments. - Types are
str,intandfloat. Anintis 64 bits. - Our oracle is Python 3.14's argparse. Another Python version may word a message differently.
The library has moved to mojo-libs under libs/args. The old repository is read-only.
Words you may not know
- Flag: an option that is on or off, such as
-q. - Positional argument: a plain word whose meaning comes from its place in the line.
- Subcommand: a word that picks a job, such as
commitingit commit. - Default: the value used when the user says nothing.
- Parser: code that reads text and turns it into structured data.
Try it
- Add the library with
pixi add mojo-argsusing the steps on the mojo-libs page. - Copy the greet program, then add an option of your own.
- Read the mojo-args README for the full list of supported actions.
- Try a wrong value on purpose and compare the message with what Python prints.
Read next
- The same small program in Python and in Mojo puts argparse and mojo-args side by side.

Reacties
Nog geen reacties.
Inloggen om te reageren.