Skip to content

Mojo Command-Line Arguments

Command-line arguments are the words you type after a program’s name, like ls -l or git commit. They let one program do different things without editing its code. In Mojo you read them with argv() from std.sys. If you know Python’s sys.argv, it’s the same idea, with a couple of Mojo twists.

The programs on this page need arguments, so each one comes with the command we ran and what it printed, under “You’ll see”. Everything was checked with Mojo 1.2 on Linux.

Here’s a program that prints every argument it gets, with its position:

from std.sys import argv
def main():
var args = argv()
print("count:", len(args))
for i in range(len(args)):
print(i, args[i])

Run it with three arguments after the file name:

Terminal window
mojo run args.mojo Ada 42 "two words"

You’ll see:

count: 4
0 args.mojo
1 Ada
2 42
3 two words

A few things to notice:

  • Item 0 is the program itself, so the first real argument is args[1]. With mojo run, item 0 is the file name; for a built program it’s the name you started it with, such as ./total.
  • Your shell splits arguments at spaces. Quotes keep words together, so "two words" arrives as one argument.
  • Everything arrives as text, even 42. You’ll turn it into a number below.

Run it with nothing after the file name and you get count: 1 and 0 args.mojo: the list is never empty.

argv() returns a Span of strings: a read-only view of the arguments, not a List you own (see Mojo Span). You can use len(), index it, loop over it, slice it and print it:

from std.sys import argv
def main():
var args = argv()
print(args)
var names: List[String] = []
for arg in args[1:]:
names.append(String(arg))
print(names)
print(len(names), "names")
Terminal window
mojo run names.mojo Ada Linus Grace

You’ll see:

[names.mojo, Ada, Linus, Grace]
[Ada, Linus, Grace]
3 names

args[1:] skips the program name. Each item is a string view, so String(arg) makes a real String to keep in your own list. You can also call string methods on an item directly, for example args[1].upper().

What if the user forgets the argument? This program assumes there’s a name:

from std.sys import argv
def main():
var args = argv()
print(t"Hello, {args[1]}!")

With mojo run hello.mojo Ada it prints Hello, Ada!. With no argument, it crashes:

At: hello.mojo:6:25: Assert Error: index 1 is out of bounds, valid range is 0 to 0
...
mojo: error: execution crashed

(The ... stands for a few lines of stack trace.) The fix is to check len(args) first and print a short usage line that tells people how to call your program:

from std.sys import argv
def main():
var args = argv()
if len(args) < 2:
print("usage: hello <name>")
return
print(t"Hello, {args[1]}!")

Now no argument gives usage: hello <name>, and mojo run hello.mojo Ada still gives Hello, Ada!.

Arguments are text, so Int(args[i]) turns one into a number. It raises an error when the text isn’t a whole number (see Mojo Type Conversion), so wrap it in try.

A good command-line tool also tells the shell whether it worked. That’s the exit code: 0 means success, anything else means something went wrong. exit(code) from std.sys stops the program with that code, and print(..., file=stderr) sends error messages to the error stream instead of normal output:

from std.sys import argv, exit, stderr
def main():
var args = argv()
if len(args) < 2:
print("usage: total <number> [number ...]", file=stderr)
exit(2)
var total = 0
for i in range(1, len(args)):
try:
total += Int(args[i])
except:
print(t"not a number: {args[i]}", file=stderr)
exit(1)
print("total:", total)
Terminal window
mojo run total.mojo 3 4 5
mojo run total.mojo 3 four
echo $?

You’ll see:

total: 12
not a number: four
1

echo $? prints the exit code of the last command, here 1. With no numbers at all, the program prints the usage line and exits with 2. Scripts and other tools check these codes, so it’s worth getting them right. Unlike Python’s sys.exit(), Mojo’s exit() doesn’t raise an exception: it stops the program right there.

Many tools take options that start with --. Mojo’s standard library has no ready-made argument parser like Python’s argparse, but for a few options a while loop does the job:

from std.sys import argv
def main():
var shout = False
var times = 1
var names: List[String] = []
var args = argv()
var i = 1
while i < len(args):
var arg = args[i]
if arg == "--shout":
shout = True
elif arg == "--times" and i + 1 < len(args):
try:
times = Int(args[i + 1])
except:
print("--times needs a number")
return
i += 1
elif arg.startswith("--"):
print(t"unknown option: {arg}")
return
else:
names.append(String(arg))
i += 1
if len(names) == 0:
names.append("world")
for name in names:
var text = String(t"Hello, {name}!")
if shout:
text = text.upper()
for _ in range(times):
print(text)
Terminal window
mojo run greet.mojo
mojo run greet.mojo Ada Linus
mojo run greet.mojo --shout --times 2 Ada
mojo run greet.mojo --loud

You’ll see:

Hello, world!
Hello, Ada!
Hello, Linus!
HELLO, ADA!
HELLO, ADA!
unknown option: --loud

We use while instead of for because --times eats the next argument too: i += 1 inside that branch skips over the number. Anything that doesn’t start with -- is treated as a name. For a bigger tool with many options, look for a community package, or keep a loop like this and add a --help branch.

mojo build doesn’t change any of this. Build once, then pass arguments straight to the program:

Terminal window
mojo build total.mojo -o total
./total 10 20 30

You’ll see:

total: 60

Inside the program, argv()[0] is now ./total. More on building in Mojo Building & Compilation Targets.

Write repeat.mojo so that mojo run repeat.mojo hi 3 prints hi three times. With the wrong number of arguments, print usage: repeat <word> <times>. If the count isn’t a number, say so.

Hint: check len(args) != 3, then use Int(args[2]) inside try.

Show solution
from std.sys import argv
def main():
var args = argv()
if len(args) != 3:
print("usage: repeat <word> <times>")
return
try:
var times = Int(args[2])
for _ in range(times):
print(args[1])
except:
print(t"'{args[2]}' isn't a whole number")
Terminal window
mojo run repeat.mojo hi 3
mojo run repeat.mojo hi x

You’ll see:

hi
hi
hi
'x' isn't a whole number

The length check runs first, so args[1] and args[2] are always safe to use.

Write largest.mojo that prints the biggest of the numbers it’s given, like largest: 17 for 4 17 -3 9. With no numbers, print a usage line.

Hint: start best at Int(args[1]), then loop over args[2:]. Marking main as raises is fine for a small tool.

Show solution
from std.sys import argv
def main() raises:
var args = argv()
if len(args) < 2:
print("usage: largest <number> [number ...]")
return
var best = Int(args[1])
for arg in args[2:]:
var n = Int(arg)
if n > best:
best = n
print("largest:", best)
Terminal window
mojo run largest.mojo 4 17 -3 9

You’ll see:

largest: 17

Because main is raises, a word like seven stops the program with Unhandled exception caught during execution and exit code 1. That’s acceptable for a quick tool; catch the error yourself when you want a friendlier message.

  • argv() from std.sys gives you the arguments as a read-only Span of strings.
  • args[0] is the program; real arguments start at args[1]. Quotes keep words together.
  • Check len(args) before indexing, or a missing argument crashes the program.
  • Arguments are text: Int(arg) raises on bad input, so use try.
  • Use exit(code) and print(..., file=stderr) from std.sys so scripts can tell success from failure.
  • There’s no argument parser in the standard library; a while loop handles a few --options.

Next up: Mojo reading input, asking the user questions while your program runs.

Quick check

1. You run mojo run app.mojo red blue. What is argv()[1]?
2. What happens with var n = Int(args[1]) when the argument is ten?
3. Which command passes -v to your program instead of to Mojo?
4. Your tool got bad input. How do you stop it so a script can see that it failed?