os
The os module connects a program to the process that runs it: command-line arguments, environment variables, the exit status, standard input and error, other programs, and signals. This page covers each and the patterns for small command-line tools.
import os
fn main():
args = os.args()
print(len(args) >= 1)
print(os.env("APP_GREETING", "hello"))true
helloargs
fn args() [str]The command-line arguments. args()[0] is the program itself (the path it was started with); the arguments you typed start at index 1. With tern run, put the program's arguments after --:
tern run wc.tn -- notes.txt todo.txt # args() == [<binary>, "notes.txt", "todo.txt"]
./wc notes.txt todo.txt # after `tern build wc.tn -o wc`Every call returns a fresh array; call it once and keep the result. Arguments are raw strings: convert numbers with to_int / to_float and a default, and check len before indexing, since reading past the end is a runtime error.
import os
fn main():
args = os.args()
count = 3
if len(args) > 1:
count = args[1].to_int(3)
names = args[1..] # everything after the program name
print(count, names)3 []For flags (--top 5, -v, --help), use the flag module rather than reading os.args() by hand: it fills a struct, checks each value's type, and writes the usage.
env
fn env(name: str, default: str) strThe value of the environment variable name, or default if it isn't set. A variable that is set to the empty string returns "", not the default. Names are case-sensitive. There is no way to set or list variables.
import os
fn main():
port = os.env("PORT", "8080").to_int(8080)
debug = os.env("APP_DEBUG", "0") == "1"
print(port, debug, os.env("PATH", "") != "")8080 false trueexit
fn exit(code: int)Ends the program at once with exit status code: 0 means success, anything else failure. Standard output is flushed first, so everything already printed appears. Nothing else runs afterwards: no code after the call, no other tasks. Operating systems keep only the low 8 bits of the status, so use 0 to 125.
Returning from main exits with status 0, and a runtime error exits with status 2, so exit is for reporting failure yourself, or for stopping early from deep inside the program.
import os
fn main():
print("checking...")
ok = true
if ok:
os.exit(0)
print("never printed")checking...eprint, read_line, read_all
fn eprint(s: str) a line to stderr
fn read_line() str the next line of stdin, with its "\n" ("" at the end)
fn read_all() str the rest of stdinErrors and progress go to stderr with eprint, so stdout stays clean for output that is piped on. In a task, waiting for input parks only the task.
run
fn run(cmd: str, args: [str]) Output
fn run_input(cmd: str, args: [str], input: str) OutputRuns a program (found on PATH), waits for it, and returns its exit status, what it printed on stdout (out) and on stderr (err). run_input also feeds it input on stdin. A status of 128 + n means signal n ended it; -1 means it couldn't be started, and then err says why. Arguments are passed as they are, with no shell in between (so no quoting or injection issues); to use shell features, run sh with -c. In a task, the wait happens on the blocking-thread pool, so other tasks keep running.
import os
fn main():
r = os.run("sh", ["-c", "echo hi; echo oops >&2; exit 3"])
print(r.status, r.out.trim(), r.err.trim())
up = os.run_input("tr", ["a-z", "A-Z"], "shout")
print(up.out)
print(os.run("no-such-command", []).status)3 hi oops
SHOUT
-1spawn
fn spawn(cmd: str, args: [str]) Process
fn spawn_with(cmd: str, args: [str], opts: ProcOpts) Process
struct ProcOpts: dir: str, env: [str], out: str, err: strStarts a program and returns while it keeps running: a server to test against, a long-running job to watch, a program to talk to over its stdin and stdout. spawn gives it pipes for stdin and stdout and lets it print to our stderr. spawn_with also says where it runs (dir, "" for here), adds "NAME=value" entries to its environment (env), and where its stdout (out: "pipe", "inherit", "null", or a file path) and stderr (err: "inherit", "out" for into its stdout, "null", or a file path) go.
| Call | What it does |
|---|---|
p.ok() bool | false if it couldn't be started; os.error() says why |
p.write(text) bool | writes to its stdin (false once it stopped reading) |
p.close_input() | closes its stdin, so a program reading to the end finishes |
p.out_line() str | the next line of its stdout, with its "\n" ("" once it closed it) |
p.out_all() str | the rest of its stdout (waits for it to close it) |
p.wait() int | waits for it to end; its exit status (128 + n if signal n ended it) |
p.wait_ms(ms) int | the same, or -1 if it's still running after ms milliseconds |
p.kill(sig) bool | sends signal sig (15 TERM, 9 KILL, 2 INT) to it and to the programs it started |
p.pid() int | its process id |
Each child gets its own process group, so kill also stops what it started (the program behind a tern run, the commands of a sh -c). In a task, reading and writing park only the task.
import os
fn main():
p = os.spawn("cat", [])
p.write("hello\n")
print(p.out_line().trim())
p.close_input()
print(p.wait())
sh = os.spawn_with("sh", ["-c", "echo $GREETING; echo oops >&2; exit 3"],
os.ProcOpts("", ["GREETING=hi"], "pipe", "out"))
print(sh.out_all().trim().replace("\n", " "), sh.wait())
slow = os.spawn("sleep", ["10"])
print(slow.wait_ms(20), slow.kill(15), slow.wait())
print(os.spawn("no-such-command", []).ok(), os.error())hello
0
hi oops 3
-1 true 143
false os.spawn: can't run no-such-command: No such file or directorycwd, chdir, setenv, error
fn cwd() str
fn chdir(dir: str) bool
fn setenv(name: str, value: str)
fn error() strcwd is the working directory; chdir changes it for the whole program (false if it can't, and os.error() says why). setenv sets a variable in the program's environment, which the programs it starts inherit (an empty value removes it). error says why the last spawn or chdir on this thread failed ("" after a success).
wait_signal
fn wait_signal() strWaits for one of SIGINT (Ctrl-C), SIGTERM (what kill and container runtimes send), SIGHUP, SIGUSR1 or SIGUSR2 and returns its name. The first call makes those signals events for the program instead of ending it, so call it early (from a task) when you want to clean up before exiting. Each signal goes to one waiter.
import os
import task
fn on_signal():
name = os.wait_signal()
os.eprint("got " + name + ", saving state")
os.exit(0)
fn main():
task.spawn(fn() on_signal())
# ... the program's work ...roost.serve handles SIGINT and SIGTERM itself: it stops accepting connections, lets the requests in progress finish (up to TERN_WEB_DRAIN_SEC seconds, default 10), and returns.
at_exit
fn at_exit(f: fn())f runs when the program ends: main returns, os.exit is called, or a runtime error ends it. Functions added later run first. A runtime error in one is printed and the others still run. A signal that kills the process (SIGKILL, or SIGTERM without a handler) runs none of them. It is for final writes: the sqlite package commits what exec_later queued this way.
import os
fn main():
os.at_exit(fn() print("closed the log"))
os.at_exit(fn() print("flushed the queue")) # added last: runs first
print("main is done")main is done
flushed the queue
closed the logon_error, last_error_report
struct ErrorReport: message: str, file: str, line: int, function: str, frames: [Frame],
image_base: int, slide: int, build_id: str, task_id: int, thread_id: int, time: int,
locals: {str: str}
struct Frame: function: str, pc: int
fn on_error(f: fn(ErrorReport))
fn last_error_report() ErrorReportFor error trackers (Sentry and the like): after os.on_error(f), every runtime error calls f with a report, including the ones something catches: a task that fails, a web handler's error that became a 500, an error inside parallel:. A report has the message as printed, the file, line and Tern function where it happened, the frames it came through (innermost first; each a Tern function name, or the C symbol, and its address), what's needed to symbolicate the addresses elsewhere (where the executable was loaded, and its build id: the Mach-O UUID or the ELF GNU build id, in hex), the task and thread, the time (nanoseconds since the Unix epoch), and the failing task's task-locals (task.local_set, up to about 4KB): the request id or trace context it was working on. f runs on a thread of its own, one report at a time, so a slow reporter never delays the code that failed; a runtime error inside f is dropped rather than reported. The error that ends the program is reported before it exits (waiting up to 3 seconds). Stack overflows aren't reported.
last_error_report() returns the most recent report (message "" when there is none), for code that learns about an error through h.join(). Reports are recorded from the first call to either function on, so programs that use neither pay nothing.
import os
import task
fn average(xs: [int]) int:
return 10 / len(xs)
fn main():
reports: chan[os.ErrorReport] = task.channel(0)
os.on_error(fn(r: os.ErrorReport) reports.send(r))
h = task.spawn(fn() average([]))
while not h.done():
task.sleep(1)
h.cancel() # (this failure is expected)
r = reports.recv()
print(r.function, r.line, len(r.frames) > 0, r.task_id > 0)average 5 true trueA complete example
A small command-line tool that counts lines, words, and bytes in the files it is given, and exits with status 1 if any file can't be read (usage: ./wc file...):
import os
import fs
fn main():
args = os.args()
if len(args) < 2:
print("usage: wc FILE...")
os.exit(64)
failed = false
total_lines = 0
for path in args[1..]:
if not fs.exists(path):
print(f"wc: {path}: no such file")
failed = true
continue
text = fs.read(path)
lines = len(text.split("\n")) - 1
words = 0
for w in text.replace("\n", " ").replace("\t", " ").split(" "):
if w != "":
words += 1
total_lines += lines
print(f"{lines} {words} {len(text)} {path}")
if len(args) > 2:
print(f"{total_lines} total")
if failed:
os.exit(1)