Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

os

import os

The os module is Zuri’s interface to the underlying operating system: environment variables, the filesystem, other processes, and the machine itself. Per-file operations: reading, writing, deleting, or copying one particular file, or inspecting its size/permissions/timestamps: live on the file class instead; see file.stats(), file.delete(), and file.copy(). Everything that isn’t about one specific already-open file lives here.

Environment variables

import os

var port = os.get_env('PORT', '8080')
os.set_env('APP_ENV', 'production')

for name in os.environ() {
  echo '${name} = ${os.environ()[name]}'
}

Paths

Paths are resolved and compared purely as strings, without touching the filesystem, so they work the same whether or not anything actually exists at the path yet.

var config = os.join_paths(os.home_dir(), '.config', 'zuri')
var absolute = os.abs_path('../lib/main.zu')
var rel = os.relative_path('/srv/app', '/srv/app/logs/out.log')
# rel == 'logs/out.log'

The filesystem

os.create_dir('build')

for entry in os.read_dir('.', false) {
  if os.is_dir(entry) continue
  echo entry
}

var git = os.which('git')  # full path, or nil if not on PATH
var sources = os.glob('*.zu')

Running other programs

exec() is the simple case: run a command, block until it finishes, get back its exit code and output.

var result = os.exec('git', 'rev-parse', 'HEAD')
if result.exit_code == 0 {
  echo 'HEAD is at ${result.output.trim()}'
}

spawn() is for everything exec() doesn’t cover: a long-running command, one that needs input written to it, or one whose output needs to be read as it arrives rather than all at once at the end.

var proc = os.spawn('grep', ['error'], { stdin: 'pipe' })
proc.write_stdin('startup ok\nerror: disk full\n')
proc.close_stdin()
echo proc.read_stdout().to_string()  # 'error: disk full\n'
proc.wait()

on_signal() traps SIGINT/SIGTERM/etc. so a long-running script can shut down cleanly instead of being torn down mid-work. Falling off the end of the callback lets the signal do what it would have done anyway, so this cleans up and then exits:

os.on_signal('INT', @() {
  echo 'shutting down...'
  flush_caches()
})

Return a truthy value instead to swallow the signal and keep running.

Windows has no signals. A callback registered there runs for console events like Ctrl+C, and never for anything kill() sends.

The machine

echo 'running on ${os.num_cpus()} cores'
echo '${os.free_memory() / 1_000_000} MB free of ${os.total_memory() / 1_000_000} MB'

Scratch space

create_temp_file()/create_temp_dir() reserve a uniquely named path under temp_dir() atomically, so two processes racing to create scratch space can never collide on the same name:

var path = os.create_temp_file('upload-', '.tmp')
file(path, 'w').write(incoming_data)
# ... use it, then clean up when done
file(path).delete()

The os API

Every public name in os, wherever it is declared. Each links to the page that documents it.

NameKindSummary
os.DT_BLKconstantBlock device file type
os.DT_CHRconstantCharacter device file type
os.DT_DIRconstantDirectory file type
os.DT_FIFOconstantNamed pipe file type
os.DT_LNKconstantSymbolic link file type
os.DT_REGconstantRegular file type
os.DT_SOCKconstantLocal-domain socket file type
os.DT_UNKNOWNconstantUnknown file type
os.DT_WHTconstantWhiteout file type (only meaningful on UNIX and some unofficial Linux versions).
os.ProcessclassA running (or finished) child process created by spawn().
os.abs_pathfunctionReturns the absolute form of path: relative paths are resolved against the current working directory, and…
os.argsconstantThe command line, as the running script sees it.
os.at_exitfunctionRegisters callback to run when the program ends.
os.base_namefunctionThe base_name() function returns the last component from the pathname pointed to by path, deleting any…
os.change_dirfunctionNavigates the working directory into the specified path.
os.chmodfunctionChanges the permission set on a directory to the given mode.
os.chownfunctionChanges the owning user and group of path to uid and gid.
os.create_dirfunctionCreates the given directory with the specified permission and optionally add new files into it if any is…
os.create_temp_dirfunctionAtomically creates a new, empty, uniquely named directory inside temp_dir() and returns its path.
os.create_temp_filefunctionAtomically creates a new, empty, uniquely named file inside temp_dir() and returns its path.
os.cwdfunctionThe current working directory.
os.dir_existsfunctionReturns true if path exists and is a directory, false otherwise (including when path exists but is a…
os.dir_namefunctionReturns the parent directory of the pathname pointed to by path.
os.environfunctionReturns every environment variable currently visible to this process as a dictionary of name/value pairs.
os.exe_pathconstantThe full path to the running Zuri executable.
os.execfunctionExecutes the given shell (or command prompt for Windows) commands and returns a dictionary containing the…
os.exitfunctionExit the current process and quits the Zuri runtime.
os.expand_userfunctionExpands a leading ~ in path into the current user’s home directory, the same way a shell would before…
os.expand_varsfunctionExpands $NAME/$NAME`` references in text (and, on Windows, %NAME% references as well) using the…
os.free_memoryfunctionAn estimate of how much physical memory is available for new allocations right now, in bytes: free memory…
os.get_envfunctionReturns the given environment variable if it exists or default_value (nil if not given) otherwise.
os.globfunctionReturns every entry under base_path (the current working directory if not given) whose path matches the…
os.home_dirfunctionThe current machine user’s home directory.
os.hostnamefunctionThe current machine’s hostname.
os.infofunctionReturns information about the current operation system and machine as a dictionary.
os.is_dirfunctionReturns true if the path is a directory or false otherwise.
os.is_symlinkfunctionReturns true if path exists and is a symbolic link, false otherwise (including when path doesn’t…
os.join_pathsfunctionConcatenates the given paths together into a format that is valid on the current operating system.
os.killfunctionSends signal to the process identified by pid.
os.num_cpusfunctionThe number of logical CPUs available to this process.
os.on_signalfunctionRegisters callback to run when this process receives the named signal, for handling things like Ctrl+C…
os.path_containsfunctionReturns true if the resolved form of candidate is base itself or lies somewhere underneath it, and…
os.path_separatorconstantThe standard path separator for the current operating system.
os.pidfunctionThe current process’s id.
os.platformconstantThe name of the current platform in string or unknown if the platform name could not be determined.
os.ppidfunctionThe current process’s parent’s id.
os.read_dirfunctionScans the given directory and returns a list of the names it contains, sorted by name, led by . and ...
os.readlinkfunctionReturns the target path points to, if path is a symbolic link.
os.real_pathfunctionReturns the original path to a relative path.
os.relative_pathfunctionReturns the relative path from base to target: the shortest ./..-based path such that, starting…
os.remove_dirfunctionDeletes a non-empty directory.
os.renamefunctionRenames the file or directory specified by old_name to the name given by new_name.
os.set_envfunctionSets the named environment variable to the given value.
os.set_exit_codefunctionRecords the status the process should end with, without ending it.
os.sleepfunctionCauses the current thread to sleep for the specified number of seconds.
os.spawnfunctionSpawns cmd as a new subprocess and returns a Process handle to it immediately, without waiting for it to…
os.targetconstantThe platform the running runtime was built for, as a target triple: x86_64-unknown-linux-gnu,…
os.temp_dirfunctionThe platform’s directory for temporary files (e.g. /tmp on Unix, whatever %TEMP% points to on Windows).
os.total_memoryfunctionThe total physical memory installed on this machine, in bytes.
os.umaskfunctionGets or sets the process’s file-creation mask: the set of permission bits stripped from every file/directory…
os.unset_envfunctionRemoves the named environment variable, if it’s set.
os.uptimefunctionHow long the machine has been running since it last booted, in seconds.
os.versionconstantThe current Zuri version.
os.vm_versionconstantThe current Zuri VM version.
os.whichfunctionSearches every directory in the PATH environment variable, in order, for an executable file named name,…

Submodules

ModuleReached asSummary
os.envos.*Reading, writing, and enumerating the current process’s environment variables.
os.fsos.*Directory and filesystem-entry operations: creating, listing, and removing directories, permissions and…
os.pathos.*Path string manipulation: joining, resolving, and comparing paths.
os.processos.*Process identity, subprocess execution, and signal handling.
os.systemos.*Facts about the current process, the Zuri runtime, and the machine it’s running on.
os.tempfileos.*Locating the platform’s temporary-file directory and creating uniquely named scratch files/directories inside…

2021, Richard Ore and Zuri contributors