Files, directories, system commands, program arguments and environment variables.
import os
The os package is the simplest way to talk to the system: whole-file reads and writes, folders, shell commands, the program's arguments and its environment. Each function does one thing and takes paths as plain strings. Reach for it in scripts, build tools and small servers. When you need to know why something failed, or to read a big file piece by piece, the fs family (fs for files, fs.dir, fs.path) does more; for building paths use filepath, and for configuration from the environment env.
Results follow two conventions. Functions that change something (Remove, Mkdir, Move, Copy, MkdirAll, RemoveAll) return 0 on success and -1 on failure, with no reason attached. WriteFile and AppendFile return the number of bytes written, or -1. Functions that read return an empty value when they fail: ReadFile gives empty text and ListDir an empty vector for a missing folder.
There are sub-packages for more specialised work: os.process for running other programs with exact arguments, os.shell for capturing command output and errors, os.platform for identifying the system, os.temp for temporary files, os.user for the current user and os.error for error codes.
What people get wrong:
•
Building a shell command from user input. Run, RunCapture and Output hand the whole string to /bin/sh, so a name such as x; rm -rf ~ runs the second command too.
•
Expecting RunCapture to capture errors. It captures standard output only; the command's standard error still goes to the terminal. Add 2>&1 to the command when you want both.
•
Running Walk on a tree with symbolic links. It follows a link to a folder as if it were a real folder, so it lists what is behind it and never ends on a link loop. RemoveAll does not follow links: it deletes the link itself and leaves its target alone.
•
Using Move across disks. It is a rename, and a rename between file systems fails with -1; copy and remove instead.
The sections below walk through the jobs this package is used for most, each with a complete program and the output it printed. The programs work in the current directory and remove what they create.
Read a settings file with defaults
A small program usually keeps its settings in a text file next to it. Exists tells you whether the file is there yet, WriteFile creates it with sensible values the first time, and ReadFile gives you the whole text to pick apart. Every setting that is missing falls back to a default, so an old file keeps working after you add a new option.
os-guide-config.salam
import os
funcsetting(text: str, key: str, fallback: str): str:
each line in text.Split("\n"):
if line.StartsWith(key + "="):
ret line.Substr(key.Len() + 1, line.Len() - key.Len() - 1)
endendret fallback
endfuncmain:
path := "app.conf"ifnot os.Exists(path):
os.WriteFile(path, "port=8080\nname=notes\n")
println"wrote a default", path
end
text := os.ReadFile(path)
println"port:", setting(text, "port", "80")
println"name:", setting(text, "name", "app")
println"debug:", setting(text, "debug", "off")
os.Remove(path)
end
Output
wrote a default app.conf
port: 8080
name: notes
debug: off
ReadFile returns an empty string both for an empty file and for one it cannot read. When the difference matters, ask Exists first, as here. For a real format, read the text with encoding.json or a similar package instead of splitting lines by hand.
Keep a log and rotate it
AppendFile adds to the end of a file and creates it when it is missing, which is all a log needs. FileSize says how big the log has become; once it passes a limit, Move renames it out of the way and the next AppendFile starts a fresh one.
os-guide-log.salam
import os
funclog(path: str, line: str):
os.AppendFile(path, line + "\n")
endfuncmain:
path := "app.log"log(path, "started")
log(path, "user sara signed in")
log(path, "stopped")
println"size:", os.FileSize(path), "bytes"
lines := os.ReadFile(path).Split("\n")
println"first entry:", lines.Get(0)
if os.FileSize(path) > 32:
os.Move(path, "app.log.1")
println"rotated:", os.Exists("app.log.1"), os.Exists(path)
endlog(path, "a fresh log")
println"new size:", os.FileSize(path)
os.Remove(path)
os.Remove("app.log.1")
end
Output
size: 36 bytes
first entry: started
rotated: true false
new size: 12
Each call opens and closes the file, which is fine for a few lines a second. For a busy log, open it once with Open(path, "ab") and write to the handle.
Create, walk and remove a directory tree
MkdirAll creates a path with every parent it needs, so the order you create folders in does not matter. Walk lists every file below a directory, at any depth, and ListDirs only the folders directly inside it. RemoveAll deletes the whole tree at the end.
os-guide-tree.salam
import os
import sort
funcmain:
os.MkdirAll("site/pages/blog")
os.MkdirAll("site/assets")
os.WriteFile("site/pages/index.salam", "func main: end")
os.WriteFile("site/pages/blog/first.salam", "func main: end")
os.WriteFile("site/assets/logo.svg", "<svg/>")
mut count := 0mut bytes := 0asi64each p in os.Walk("site"):
if p.EndsWith(".salam"):
count++
bytes += os.FileSize(p)
endendprintln"source files:", count, "with", bytes, "bytes"
folders := os.ListDirs("site")
sort.Sort(folders)
each name in folders:
println"folder:", name
end
os.RemoveAll("site")
println"cleaned up:", not os.Exists("site")
end
Walk returns full paths that start with the folder you gave it, while ListDir and ListDirs return bare names, hidden ones included and . and .. left out. The system returns directory entries in no particular order, and the order changes between file systems. Sort the names, as the program does with sort, before you print them or compare them with something.
Run shell commands and check them
Run, RunCapture and Output pass the command to the system shell, so pipes, redirection and quoting work just as they do in a terminal. Run only gives back the exit code, and the command prints straight to the program's own output; that is enough to ask whether a tool is installed. RunCapture gives the code and the standard output together, and Output only the text, final newline included, so trim it.
os-guide-commands.salam
import os
functool_exists(name: str): bool:
ret os.Run("command -v " + name + " > /dev/null") == 0endfuncmain:
println"sh available:", tool_exists("sh")
println"made-up tool available:", tool_exists("no-such-tool-here")
r := os.RunCapture("printf 'b\\na\\nc\\n' | sort")
if r.code != 0:
printerrln"sort failed with", r.code
ret1endprint r.out
count := os.Output("printf 'x\\ny\\n' | wc -l").Trim()
println"lines counted by wc:", count
end
Output
sh available: true
made-up tool available: false
a
b
c
lines counted by wc: 2
Because a shell reads the command, never build one from text a user typed: a name such as x; rm -rf ~ would run the second command too. To pass untrusted values, use os.process, which hands each argument to the program untouched.
Which function for which job
Job
Function
Read or replace a whole small file
ReadFile, WriteFile
Add lines to a log
AppendFile
Read a big file piece by piece
Open, then the handle's readline and close
Know if a path is there, and what it is
Exists, IsDir, or Stat for everything at once
Make or delete folders
MkdirAll, RemoveAll (Mkdir and Rmdir for one level)
Deletes a file or a directory with everything inside it; a missing path counts as success. Take care: it cannot be undone. A symbolic link is deleted as a link; it is never followed, so its target stays.
The example for this item is shown with the ones above: os-Dirs.salam
The value of an environment variable, or an empty string when it is not set (so an empty and a missing variable look the same). The env package does more.
The example for this item is shown with the ones above: os-Args.salam
The names of everything inside a directory, hidden entries included, without . and .. and without descending into subdirectories. A missing directory gives an empty vector.
The example for this item is shown with the ones above: os-Dirs.salam
The paths of every file inside a directory and its subdirectories, each starting with root; the directories themselves are not in the list. It follows symbolic links to directories, so a link loop never ends.
The example for this item is shown with the ones above: os-Dirs.salam
The absolute path with every symbolic link resolved, or empty text when the path does not exist. Compare these, not the paths you were given, when checking that a file stays inside a folder.
The example for this item is shown with the ones above: os-Dirs.salam
Creates or replaces a file with data and returns the number of bytes written, or -1 when the file cannot be opened (for example when its folder does not exist).
The example for this item is shown with the ones above: os-Files.salam
Runs a command in the system shell (/bin/sh, or cmd on Windows) and returns its exit code; the command's output goes straight to the program's own output.
The example for this item is shown with the ones above: os-Run.salam
Runs a command and returns its exit code and its standard output together in a CmdResult. Standard error is not captured; append 2>&1 for it. When the shell cannot be started, code is -1.
The example for this item is shown with the ones above: os-Run.salam