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.
Reading arguments with argv()
Section titled “Reading arguments with argv()”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:
mojo run args.mojo Ada 42 "two words"You’ll see:
count: 40 args.mojo1 Ada2 423 two wordsA few things to notice:
- Item
0is the program itself, so the first real argument isargs[1]. Withmojo 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.
What argv() gives you
Section titled “What argv() gives you”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")mojo run names.mojo Ada Linus GraceYou’ll see:
[names.mojo, Ada, Linus, Grace][Ada, Linus, Grace]3 namesargs[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().
Check the length before you index
Section titled “Check the length before you index”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!.
Numbers, errors and exit codes
Section titled “Numbers, errors and exit codes”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)mojo run total.mojo 3 4 5mojo run total.mojo 3 fourecho $?You’ll see:
total: 12not a number: four1echo $? 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.
Options like --shout
Section titled “Options like --shout”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)mojo run greet.mojomojo run greet.mojo Ada Linusmojo run greet.mojo --shout --times 2 Adamojo run greet.mojo --loudYou’ll see:
Hello, world!Hello, Ada!Hello, Linus!HELLO, ADA!HELLO, ADA!unknown option: --loudWe 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.
Arguments in a built program
Section titled “Arguments in a built program”mojo build doesn’t change any of this. Build once, then pass arguments straight to the program:
mojo build total.mojo -o total./total 10 20 30You’ll see:
total: 60Inside the program, argv()[0] is now ./total. More on building in Mojo Building & Compilation Targets.
Practice
Section titled “Practice”1. Repeat a word
Section titled “1. Repeat a word”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")mojo run repeat.mojo hi 3mojo run repeat.mojo hi xYou’ll see:
hihihi'x' isn't a whole numberThe length check runs first, so args[1] and args[2] are always safe to use.
2. The largest number
Section titled “2. The largest number”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)mojo run largest.mojo 4 17 -3 9You’ll see:
largest: 17Because 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()fromstd.sysgives you the arguments as a read-onlySpanof strings.args[0]is the program; real arguments start atargs[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 usetry. - Use
exit(code)andprint(..., file=stderr)fromstd.sysso scripts can tell success from failure. - There’s no argument parser in the standard library; a
whileloop handles a few--options.
Next up: Mojo reading input, asking the user questions while your program runs.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”argvreference: the official docs forargv(), with a short example.exitreference: howexit()works in Mojo and how it differs from Python.- mojo run: the options Mojo itself takes before the file name.
- Python’s
sys.argv: the Python version, if you want to compare.