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.
| Name | Kind | Summary |
|---|---|---|
os.DT_BLK | constant | Block device file type |
os.DT_CHR | constant | Character device file type |
os.DT_DIR | constant | Directory file type |
os.DT_FIFO | constant | Named pipe file type |
os.DT_LNK | constant | Symbolic link file type |
os.DT_REG | constant | Regular file type |
os.DT_SOCK | constant | Local-domain socket file type |
os.DT_UNKNOWN | constant | Unknown file type |
os.DT_WHT | constant | Whiteout file type (only meaningful on UNIX and some unofficial Linux versions). |
os.Process | class | A running (or finished) child process created by spawn(). |
os.abs_path | function | Returns the absolute form of path: relative paths are resolved against the current working directory, and… |
os.args | constant | The command line, as the running script sees it. |
os.at_exit | function | Registers callback to run when the program ends. |
os.base_name | function | The base_name() function returns the last component from the pathname pointed to by path, deleting any… |
os.change_dir | function | Navigates the working directory into the specified path. |
os.chmod | function | Changes the permission set on a directory to the given mode. |
os.chown | function | Changes the owning user and group of path to uid and gid. |
os.create_dir | function | Creates the given directory with the specified permission and optionally add new files into it if any is… |
os.create_temp_dir | function | Atomically creates a new, empty, uniquely named directory inside temp_dir() and returns its path. |
os.create_temp_file | function | Atomically creates a new, empty, uniquely named file inside temp_dir() and returns its path. |
os.cwd | function | The current working directory. |
os.dir_exists | function | Returns true if path exists and is a directory, false otherwise (including when path exists but is a… |
os.dir_name | function | Returns the parent directory of the pathname pointed to by path. |
os.environ | function | Returns every environment variable currently visible to this process as a dictionary of name/value pairs. |
os.exe_path | constant | The full path to the running Zuri executable. |
os.exec | function | Executes the given shell (or command prompt for Windows) commands and returns a dictionary containing the… |
os.exit | function | Exit the current process and quits the Zuri runtime. |
os.expand_user | function | Expands a leading ~ in path into the current user’s home directory, the same way a shell would before… |
os.expand_vars | function | Expands $NAME/$NAME`` references in text (and, on Windows, %NAME% references as well) using the… |
os.free_memory | function | An estimate of how much physical memory is available for new allocations right now, in bytes: free memory… |
os.get_env | function | Returns the given environment variable if it exists or default_value (nil if not given) otherwise. |
os.glob | function | Returns every entry under base_path (the current working directory if not given) whose path matches the… |
os.home_dir | function | The current machine user’s home directory. |
os.hostname | function | The current machine’s hostname. |
os.info | function | Returns information about the current operation system and machine as a dictionary. |
os.is_dir | function | Returns true if the path is a directory or false otherwise. |
os.is_symlink | function | Returns true if path exists and is a symbolic link, false otherwise (including when path doesn’t… |
os.join_paths | function | Concatenates the given paths together into a format that is valid on the current operating system. |
os.kill | function | Sends signal to the process identified by pid. |
os.num_cpus | function | The number of logical CPUs available to this process. |
os.on_signal | function | Registers callback to run when this process receives the named signal, for handling things like Ctrl+C… |
os.path_contains | function | Returns true if the resolved form of candidate is base itself or lies somewhere underneath it, and… |
os.path_separator | constant | The standard path separator for the current operating system. |
os.pid | function | The current process’s id. |
os.platform | constant | The name of the current platform in string or unknown if the platform name could not be determined. |
os.ppid | function | The current process’s parent’s id. |
os.read_dir | function | Scans the given directory and returns a list of the names it contains, sorted by name, led by . and ... |
os.readlink | function | Returns the target path points to, if path is a symbolic link. |
os.real_path | function | Returns the original path to a relative path. |
os.relative_path | function | Returns the relative path from base to target: the shortest ./..-based path such that, starting… |
os.remove_dir | function | Deletes a non-empty directory. |
os.rename | function | Renames the file or directory specified by old_name to the name given by new_name. |
os.set_env | function | Sets the named environment variable to the given value. |
os.set_exit_code | function | Records the status the process should end with, without ending it. |
os.sleep | function | Causes the current thread to sleep for the specified number of seconds. |
os.spawn | function | Spawns cmd as a new subprocess and returns a Process handle to it immediately, without waiting for it to… |
os.target | constant | The platform the running runtime was built for, as a target triple: x86_64-unknown-linux-gnu,… |
os.temp_dir | function | The platform’s directory for temporary files (e.g. /tmp on Unix, whatever %TEMP% points to on Windows). |
os.total_memory | function | The total physical memory installed on this machine, in bytes. |
os.umask | function | Gets or sets the process’s file-creation mask: the set of permission bits stripped from every file/directory… |
os.unset_env | function | Removes the named environment variable, if it’s set. |
os.uptime | function | How long the machine has been running since it last booted, in seconds. |
os.version | constant | The current Zuri version. |
os.vm_version | constant | The current Zuri VM version. |
os.which | function | Searches every directory in the PATH environment variable, in order, for an executable file named name,… |
Submodules
| Module | Reached as | Summary |
|---|---|---|
os.env | os.* | Reading, writing, and enumerating the current process’s environment variables. |
os.fs | os.* | Directory and filesystem-entry operations: creating, listing, and removing directories, permissions and… |
os.path | os.* | Path string manipulation: joining, resolving, and comparing paths. |
os.process | os.* | Process identity, subprocess execution, and signal handling. |
os.system | os.* | Facts about the current process, the Zuri runtime, and the machine it’s running on. |
os.tempfile | os.* | Locating the platform’s temporary-file directory and creating uniquely named scratch files/directories inside… |
2021, Richard Ore and Zuri contributors