Checking how many agents are working

How this works
Contatti
← Blog
A cinematic photograph of a steel control panel with three toggle switches and one dial, one switch flipped and lit with amber light, in teal and steel, the AMARBARO mark and wordmark centred over it.
✎post del blog

Command-line options in Mojo, the way Python does them

The short version

mojo-args parses flags, values and subcommands the way Python's argparse does and prints argparse's usage-error text, but its --help page is simpler.

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.

  1. ArgumentParser("greet") makes a parser. The text is the program's name, used in messages.
  2. add_argument("name") adds a required word, which we call a positional argument.
  3. add_argument("--times", type="int", default="1") adds an option with a value. It must be a whole number. It defaults to 1.
  4. 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.
  5. parse_args(...) reads a list of words. To read the real command line, call parse_args() with no list.
  6. get_str, get_int and get_bool take 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=3 works the same as --times 3.
  • -n5 works as -n 5 for 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 --help page 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 @file arguments.
  • Types are str, int and float. An int is 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 commit in git commit.
  • Default: the value used when the user says nothing.
  • Parser: code that reads text and turns it into structured data.

Try it

  1. Add the library with pixi add mojo-args using the steps on the mojo-libs page.
  2. Copy the greet program, then add an option of your own.
  3. Read the mojo-args README for the full list of supported actions.
  4. Try a wrong value on purpose and compare the message with what Python prints.

Commenti

Ancora nessun commento.

Accedi per commentare.