Skip to content

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.

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()}")
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)
0
hello
3

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())
apple
fig
pear
0
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.3
rm: not allowed by this program's process permission
-1
import os
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() -> i64

Unix time in whole seconds. The time module builds dates and times on it: use time.now() for a DateTime.

pub fn processes() -> Processes

This program’s own permission to start programs; the compiler allows it only in the main file.

pub fn cwd() -> Str
pub fn millis() -> i64

Milliseconds 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)
true
pub fn sleep(milliseconds: i64)

Takes milliseconds as an i64. time.sleep(&time.seconds(1)) does the same with a Duration.

pub fn utc_offset(at: i64) -> i64

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

pub struct SpawnError {
pub program: Str
pub message: Str
}
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).

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.

pub fn only(&self, programs: &Vec<Str>) -> Processes

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

pub fn allows(&self, program: &Str) -> bool
pub fn run(&self, command: &Vec<Str>) -> i64 ! SpawnError

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

pub fn run_output(&self, command: &Vec<Str>) -> Output ! SpawnError

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

pub fn spawn(&self, command: &Vec<Str>) -> Process ! SpawnError

Starts a program without waiting; the Process must then be waited for or killed.

pub struct PipeError {
pub message: Str
}
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.

fn drop(&mut self)
pub fn write(&mut self, text: &Str) ! PipeError

Sends text to the program’s input.

pub fn close_input(&mut self)

Closing its input tells the program there is nothing more to read.

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.

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.

pub fn read_all(&mut self) -> Untrusted<Str>

Everything the program prints from now until it closes its output.

pub fn wait(self) -> i64

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

pub fn kill(self) -> i64

Stops the program at once (SIGKILL) and collects it; the exit code is -1.

pub fn id(&self) -> i64