Lesson 16 of 26
Building and running a real program
A real program takes arguments, reads files or input, looks at environment variables, and reports errors with an exit code. This lesson builds a small word counter, step by step, next to the same program in Python.
Each example shows how you run it. In Rust, cargo run -- notes.txt builds and runs the program. Everything
after -- goes to your program, not to Cargo. The built program in target/debug/ takes the
same arguments.
Arguments: sys.argv and env::args()
env::args() is sys.argv. The first item is the program itself, so you skip it. For
real tools with flags and --help, Rust code uses the clap crate, the
argparse/click of Rust.
import sys
args = sys.argv[1:]
print(f"{len(args)} arguments")
for arg in args:
print(arg)use std::env;
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
println!("{} arguments", args.len());
for arg in &args {
println!("{arg}");
}
}3 arguments
notes.txt
--top
3Reading a file
fs::read_to_string is open(path).read(). Reading can fail, so it returns a
Result (lesson 12). Here .expect(...) stops the program with a message if anything goes
wrong. The next example handles errors properly.
import sys
path = sys.argv[1]
with open(path) as f:
text = f.read()
words = len(text.split())
print(f"{path}: {words} words")use std::env;
use std::fs;
fn main() {
let path = env::args().nth(1).expect("usage: count <file>");
let text = fs::read_to_string(&path).expect("could not read the file");
let words = text.split_whitespace().count();
println!("{path}: {words} words");
}notes.txt: 6 wordsErrors go to stderr, with an exit code
A good command-line tool prints errors to stderr and exits with a non-zero code, so scripts and CI
can tell that it failed. eprintln! is print(..., file=sys.stderr). Returning an
ExitCode from main is sys.exit(main()). Here the file does not exist.
import sys
def main() -> int:
if len(sys.argv) < 2:
print("usage: count <file>", file=sys.stderr)
return 2
path = sys.argv[1]
try:
with open(path) as f:
text = f.read()
except OSError as e:
print(f"error: cannot read {path}: {e.strerror}", file=sys.stderr)
return 1
print(f"{path}: {len(text.split())} words")
return 0
sys.exit(main())use std::env;
use std::fs;
use std::process::ExitCode;
fn main() -> ExitCode {
let Some(path) = env::args().nth(1) else {
eprintln!("usage: count <file>");
return ExitCode::from(2);
};
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) => {
eprintln!("error: cannot read {path}: {e}");
return ExitCode::FAILURE;
}
};
println!("{path}: {} words", text.split_whitespace().count());
ExitCode::SUCCESS
}Environment variables
env::var("NAME") is os.environ["NAME"]. It returns a Result,
because the variable may not be set. .unwrap_or(...) supplies a default, like
os.environ.get(name, default).
import os
name = os.environ.get("GREETING_NAME", "world")
print(f"Hello, {name}!")use std::env;
fn main() {
let name = env::var("GREETING_NAME").unwrap_or(String::from("world"));
println!("Hello, {name}!");
}Hello, Ferris!Reading stdin
Command-line tools often read from a pipe: cat notes.txt | cargo run or
cargo run < notes.txt. io::stdin().lines() is for line in sys.stdin.
import sys
lines = 0
words = 0
for line in sys.stdin:
lines += 1
words += len(line.split())
print(f"{lines} lines, {words} words")use std::io;
fn main() {
let mut lines = 0;
let mut words = 0;
for line in io::stdin().lines() {
let line = line.expect("could not read stdin");
lines += 1;
words += line.split_whitespace().count();
}
println!("{lines} lines, {words} words");
}2 lines, 6 wordsShip it in a Docker image
For anything you measure or ship, build with cargo build --release or run with
cargo run --release -- notes.txt. A debug build can be many times slower (lesson 18).
To run the tool on a server, a two-stage Dockerfile builds with the full Rust image and then copies only the finished program into a small image. The Python image needs Python and your code. The Rust image needs just the one file. Both images below are built and run with the word counter from the "Errors go to stderr" example.
FROM python:3.12-slim
WORKDIR /app
COPY main.py .
ENTRYPOINT ["python", "main.py"]FROM rust:1-slim-bookworm AS build
WORKDIR /src
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
COPY --from=build /src/target/release/count /usr/local/bin/count
ENTRYPOINT ["count"]Where the Python analogy breaks
env::args()starts with the program name, likesys.argv, but it is an iterator, not a list. Use.nth(1), or.collect()it into aVecto index it.- Reading a file returns a
Result. There's no exception when the file is missing; you decide what happens withmatch,?orexpect. - The program is a binary, not a script. After
cargo build --releaseyou ship one file fromtarget/release/, and the server doesn't need Rust. That's why the Docker example builds in one image and runs in a much smaller one. - A panic exits with code 101, not 1 like an uncaught Python exception. For a clean exit code, return
ExitCodefrommainor callstd::process::exit.
Cheat card
| Python | Rust |
|---|---|
sys.argv | std::env::args() // the program comes first, like argv[0] |
sys.argv[1] | env::args().nth(1) // an Option |
argparse / click | clap // a crate |
python main.py notes.txt | cargo run -- notes.txt |
open(path).read() | fs::read_to_string(&path) // a Result |
for line in sys.stdin: | for line in io::stdin().lines() { |
os.environ.get("NAME", "x") | env::var("NAME").unwrap_or(String::from("x")) |
print(msg, file=sys.stderr) | eprintln!("{msg}"); |
sys.exit(main()) | fn main() -> ExitCode { ... } |
sys.exit(2) | std::process::exit(2); |
# no build step | cargo run --release -- notes.txt |
two [project.scripts] | src/bin/stats.rs + cargo run --bin stats |
← Reading compiler errors Cargo in depth: dependencies and workspaces →