Rust for Pythonistas

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.

Python
import sys

args = sys.argv[1:]
print(f"{len(args)} arguments")
for arg in args:
    print(arg)
Rust
use std::env;

fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    println!("{} arguments", args.len());
    for arg in &args {
        println!("{arg}");
    }
}
Output
3 arguments
notes.txt
--top
3

Reading 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.

Python
import sys

path = sys.argv[1]
with open(path) as f:
    text = f.read()
words = len(text.split())
print(f"{path}: {words} words")
Rust
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");
}
Output
notes.txt: 6 words

Errors 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.

Python
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())
Rust
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).

Python
import os

name = os.environ.get("GREETING_NAME", "world")
print(f"Hello, {name}!")
Rust
use std::env;

fn main() {
    let name = env::var("GREETING_NAME").unwrap_or(String::from("world"));
    println!("Hello, {name}!");
}
Output
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.

Python
import sys

lines = 0
words = 0
for line in sys.stdin:
    lines += 1
    words += len(line.split())
print(f"{lines} lines, {words} words")
Rust
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");
}
Output
2 lines, 6 words

Ship 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.

Dockerfile · Python
FROM python:3.12-slim
WORKDIR /app
COPY main.py .

ENTRYPOINT ["python", "main.py"]
Dockerfile · Rust
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

Cheat card

PythonRust
sys.argvstd::env::args() // the program comes first, like argv[0]
sys.argv[1]env::args().nth(1) // an Option
argparse / clickclap // a crate
python main.py notes.txtcargo 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 stepcargo run --release -- notes.txt
two [project.scripts]src/bin/stats.rs + cargo run --bin stats

← Reading compiler errors Cargo in depth: dependencies and workspaces →