os
The program’s surroundings: command-line arguments, environment variables, the current folder, exit codes, and starting other programs.
Starting programs needs a permission, an os.Processes value. Only the program’s main file can make one with os.processes(); it is then passed to the code that may start programs, which takes &os.Processes. A library cannot start programs unless its caller hands it this value, and only narrows it to a list of program names first.
Commands are lists of arguments, never one string, so no shell is involved and arguments need no quoting. A program’s output comes back as Untrusted<Str>: read it with unchecked() or one of the checks on Untrusted.
Arguments, environment and exit code
Section titled “Arguments, environment and exit code”import os
let args = os.args()if args.len() < 2 { eprint(f"usage: {args[0]} <name>") os.exit(2)}let home = os.env("HOME").unwrap_or("/")print(f"hello {args[1]}, home is {home}, working in {os.cwd()}")Run a program and read its output
Section titled “Run a program and read its output”import os
let procs = os.processes()let out = try procs.run_output(&["echo", "hello"])print(out.status)print(out.out.unchecked().trim())let code = try procs.run(&["sh", "-c", "exit 3"])print(code)0hello3Talk to a running program
Section titled “Talk to a running program”spawn starts a program without waiting. Write to its input, read its output, and end with wait() or kill().
import os
let procs = os.processes()let mut p = try procs.spawn(&["sort"])try p.write("pear\napple\nfig\n")p.close_input()while true { match p.read_line() { Some(line) => print(line.unchecked()) None => break }}print(p.wait())applefigpear0Pass a narrowed permission on
Section titled “Pass a narrowed permission on”import os
fn version(procs: &os.Processes) -> Str ! os.SpawnError { let out = try procs.run_output(&["echo", "1.2.3"]) return out.out.unchecked().trim()}
let procs = os.processes()print(try version(&procs.only(&["echo"])))let code = procs.only(&["git"]).run(&["rm", "-rf", "/tmp/x"]) catch { os.SpawnError(e) => { print(f"{e.program}: {e.message}") -1 }}print(code)1.2.3rm: not allowed by this program's process permission-1Reference
Section titled “Reference”import osFunctions
Section titled “Functions”pub fn args() -> Vec<Str>pub fn env(name: &Str) -> Option<Str>pub fn exit(code: i64)Ends the program at once with this code. Values still alive are not dropped, so a TempDir is not removed and a spawned Process is not waited for.
pub fn time() -> i64Unix time in whole seconds. The time module builds dates and times on it: use time.now() for a DateTime.
processes
Section titled “processes”pub fn processes() -> ProcessesThis program’s own permission to start programs; the compiler allows it only in the main file.
pub fn cwd() -> Strmillis
Section titled “millis”pub fn millis() -> i64Milliseconds from a steady clock, for measuring how long something takes.
A steady clock that never jumps back, in milliseconds since an unspecified moment. Only differences between two calls mean something.
import os
let start = os.millis()os.sleep(20)print(os.millis() - start >= 20)truepub fn sleep(milliseconds: i64)Takes milliseconds as an i64. time.sleep(&time.seconds(1)) does the same with a Duration.
utc_offset
Section titled “utc_offset”pub fn utc_offset(at: i64) -> i64Seconds the local time zone is ahead of UTC at the moment at (Unix seconds).
Seconds the local time zone is ahead of UTC at the Unix time at; it changes across daylight saving time. time.now_local() uses it.
SpawnError
Section titled “SpawnError”pub struct SpawnError { pub program: Str pub message: Str}Output
Section titled “Output”pub struct Output { pub status: i64 pub out: Untrusted<Str> pub err: Untrusted<Str>}What a program printed comes from outside this one, so it is Untrusted (out, err).
Processes
Section titled “Processes”pub struct Processes {}Permission to start programs; only the program’s main file can make one, and passes it on.
It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Processes.only
Section titled “Processes.only”pub fn only(&self, programs: &Vec<Str>) -> ProcessesThe same permission, limited to these program names.
Names are compared with the first item of the command exactly as written: only(&["git"]) allows ["git", ...] but not ["/usr/bin/git", ...]. Calling only on an already narrowed permission keeps only names allowed by both, so a library cannot widen what it was given.
Processes.allows
Section titled “Processes.allows”pub fn allows(&self, program: &Str) -> boolProcesses.run
Section titled “Processes.run”pub fn run(&self, command: &Vec<Str>) -> i64 ! SpawnErrorRuns a program and waits; the exit code, or -1 if it was killed by a signal.
The child’s output and errors go straight to this program’s own. Use run_output to collect them instead. The result is the exit code, or -1 if the program was killed by a signal. A program that cannot be started (not found, not executable) is a SpawnError; a program that runs and fails is not, so check the code.
Processes.run_output
Section titled “Processes.run_output”pub fn run_output(&self, command: &Vec<Str>) -> Output ! SpawnErrorRuns a program and collects what it printed; status is -1 if it was killed by a signal.
Waits for the program to end and holds all of its output in memory. For a program that prints a lot, or runs for a long time, use spawn and read as it goes.
Processes.spawn
Section titled “Processes.spawn”pub fn spawn(&self, command: &Vec<Str>) -> Process ! SpawnErrorStarts a program without waiting; the Process must then be waited for or killed.
PipeError
Section titled “PipeError”pub struct PipeError { pub message: Str}Process
Section titled “Process”pub struct Process {}A running program with its input and output connected to this one; its errors go to ours.
A Process is a Finish type: every one must end with wait() or kill(), and forgetting is a compile error. If code leaves early (a try that fails, a return), the process is killed and collected.
The started program’s standard error goes to this program’s standard error; only standard output is connected to read_line, read and read_all.
It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Implements Finish.
Process.drop
Section titled “Process.drop”fn drop(&mut self)Process.write
Section titled “Process.write”pub fn write(&mut self, text: &Str) ! PipeErrorSends text to the program’s input.
Process.close_input
Section titled “Process.close_input”pub fn close_input(&mut self)Closing its input tells the program there is nothing more to read.
Process.read_line
Section titled “Process.read_line”pub fn read_line(&mut self) -> Option<Untrusted<Str>>The next line the program printed, without its line ending, or None once it closed its output.
Process.read
Section titled “Process.read”pub fn read(&mut self, max: i64) -> Untrusted<Str>Up to max bytes of output, waiting only if none have arrived yet; empty at the end.
Returns as soon as some output is there, up to max bytes. An empty result means the program closed its output.
Process.read_all
Section titled “Process.read_all”pub fn read_all(&mut self) -> Untrusted<Str>Everything the program prints from now until it closes its output.
Process.wait
Section titled “Process.wait”pub fn wait(self) -> i64Closes its input, discards output not yet read, and returns the exit code (-1 if killed).
Closes the program’s input first and throws away output that was not read. Read what you need before calling it.
Process.kill
Section titled “Process.kill”pub fn kill(self) -> i64Stops the program at once (SIGKILL) and collects it; the exit code is -1.
Process.id
Section titled “Process.id”pub fn id(&self) -> i64