Standard library · System and tools

os

Files, directories, system commands, program arguments and environment variables.

import os
On this page
  1. Types
  2. Functions

The os package is the simplest way to talk to the system: each function does one thing, and most of them take a file or directory path as a string. The functions that change something, such as Remove and Mkdir, return zero on success and some other number otherwise.

There are sub-packages for more specialised work: os.process for running other programs, os.shell for capturing command output, os.platform for identifying the system, and the fs.file and fs.dir packages, which do more.

Types

FileInfo

struct FileInfo
What Stat returns.
NameTypeDescription
sizei64 = 0The size of the file in bytes.
is_dirbool = falseTrue when the path is a directory.
existsbool = falseTrue when the path exists.
os-Files.salam
import os

func main:
    os.WriteFile("note.txt", "first line\n")
    os.AppendFile("note.txt", "second line\n")
    print os.ReadFile("note.txt")
    println os.Exists("note.txt"), os.FileSize("note.txt")
    info := os.Stat("note.txt")
    println info.exists, info.is_dir, info.size
    os.Copy("note.txt", "copy.txt")
    os.Move("copy.txt", "new name.txt")
    println os.Exists("copy.txt"), os.Exists("new name.txt")
    os.Remove("new name.txt")
    println os.Exists("new name.txt")
    f := os.Open("note.txt", "rb")
    println f.readline()
    f.close()
end
Outputfirst line second line true 23 true false 23 false true false first line

CmdResult

struct CmdResult
The result of running a command with RunCapture.
NameTypeDescription
codeint = 0The command's exit code; zero means success.
outstr = ""The command's output.
os-Run.salam
import os

func main:
    code := os.Run("echo from the shell")
    println "exit code:", code
    r := os.RunCapture("echo hello")
    println r.code, "[" + r.out + "]"
    println "[" + os.Output("echo world") + "]"
    println os.Pid() > 0
end
Outputfrom the shell exit code: 0 0 [hello ] [world ] true

Functions

Open

func Open(path: str, mode: str): File*
Opens a file in the given mode: "rb" to read, "wb" to rewrite and "ab" to append. It returns null when it cannot.

The example for this item is shown with the ones above: os-Files.salam

Exit

func Exit(code: int)
Ends the program immediately with the given code. Inside main write ret instead, because exiting does not run the defer statements (error E109).
os-Args.salam
import os

func fail(message: str):
    printerrln message
    os.Exit(2)
end

func give_up():
    os.Abort()
end

func main:
    args := os.Args()
    println "argument count:", args.len()
    home := os.Env("HOME")
    println home.len() > 0 or os.Env("USERPROFILE").len() > 0
    if args.len() > 10:
        fail("too many arguments")
    end
    if args.len() > 100:
        give_up()
    end
end
Outputargument count: 1 true

Abort

func Abort()
Stops the program abruptly with an error, for a situation with no way to carry on.

The example for this item is shown with the ones above: os-Args.salam

Args

func Args(): Vector<str>
The program's command line arguments; element zero is the program's own name.

The example for this item is shown with the ones above: os-Args.salam

Env

func Env(name: str): str
The value of an environment variable, or an empty string when it is not set. The env package does more.

The example for this item is shown with the ones above: os-Args.salam

Remove

func Remove(path: str): int
Deletes a file.

The example for this item is shown with the ones above: os-Files.salam

Mkdir

func Mkdir(path: str): int
Creates a directory; the parent has to exist already.
os-Dirs.salam
import os

func main:
    os.Mkdir("project")
    os.MkdirAll("project/src/helpers")
    os.WriteFile("project/readme.txt", "hello")
    os.WriteFile("project/src/main.salam", "func main: end")
    println os.IsDir("project"), os.IsDir("project/readme.txt")
    println os.ListDir("project/src").len(), os.ListDirs("project")
    println os.Walk("project").len()
    os.CopyTree("project", "backup")
    println os.Exists("backup/src/main.salam")
    start := os.Cwd()
    os.Chdir("project")
    println os.Exists("readme.txt")
    os.Chdir(start)
    os.Rmdir("project/src/helpers")
    os.RemoveAll("project")
    os.RemoveAll("backup")
    println os.Exists("project"), os.TempDir().len() > 0
end
Outputtrue false 2 ["src"] 2 true true false true

Rmdir

func Rmdir(path: str): int
Deletes an empty directory.

The example for this item is shown with the ones above: os-Dirs.salam

Copy

func Copy(src: str, dst: str): int
Copies a file.

The example for this item is shown with the ones above: os-Files.salam

Move

func Move(src: str, dst: str): int
Moves or renames a file or a directory.

The example for this item is shown with the ones above: os-Files.salam

ListDir

func ListDir(path: str): Vector<str>
The names of everything inside a directory, without descending into subdirectories.

The example for this item is shown with the ones above: os-Dirs.salam

IsDir

func IsDir(path: str): bool
True when the path is a directory.

The example for this item is shown with the ones above: os-Dirs.salam

Walk

func Walk(root: str): Vector<str>
The paths of every file inside a directory and its subdirectories; the directories themselves are not in the list.

The example for this item is shown with the ones above: os-Dirs.salam

Exists

func Exists(path: str): bool
True when the path, file or directory, exists.

The example for this item is shown with the ones above: os-Files.salam

Cwd

func Cwd(): str
The program's current directory.

The example for this item is shown with the ones above: os-Dirs.salam

Chdir

func Chdir(path: str): int
Changes the current directory; later relative paths are resolved from there.

The example for this item is shown with the ones above: os-Dirs.salam

TempDir

func TempDir(): str
The system's temporary directory, such as /tmp.

The example for this item is shown with the ones above: os-Dirs.salam

ReadFile

func ReadFile(path: str): str
Reads the whole content of a file, or an empty string when it cannot.

The example for this item is shown with the ones above: os-Files.salam

WriteFile

func WriteFile(path: str, data: str): int
Rewrites a file.

The example for this item is shown with the ones above: os-Files.salam

AppendFile

func AppendFile(path: str, data: str): int
Adds to the end of a file.

The example for this item is shown with the ones above: os-Files.salam

FileSize

func FileSize(path: str): i64
The size of a file in bytes, or minus one when it is not there.

The example for this item is shown with the ones above: os-Files.salam

Stat

func Stat(path: str): FileInfo
Returns everything about a path at once; when the path is absent, exists is false.

The example for this item is shown with the ones above: os-Files.salam

MkdirAll

func MkdirAll(path: str): int
Creates a directory along with every parent it needs, and does nothing when it already exists.

The example for this item is shown with the ones above: os-Dirs.salam

RemoveAll

func RemoveAll(path: str): int
Deletes a file or a directory with everything inside it. Take care; it cannot be undone.

The example for this item is shown with the ones above: os-Dirs.salam

CopyTree

func CopyTree(src: str, dst: str): int
Copies a directory with all its subdirectories and files.

The example for this item is shown with the ones above: os-Dirs.salam

ListDirs

func ListDirs(path: str): Vector<str>
Only the names of a directory's subdirectories.

The example for this item is shown with the ones above: os-Dirs.salam

Run

func Run(cmd: str): int
Runs a command in the system shell 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

RunCapture

func RunCapture(cmd: str): CmdResult
Runs a command and returns its exit code and its output together in a CmdResult.

The example for this item is shown with the ones above: os-Run.salam

Output

func Output(cmd: str): str
Runs a command and returns only its output text, including the final newline.

The example for this item is shown with the ones above: os-Run.salam

Pid

func Pid(): int
The process id of the running program.

The example for this item is shown with the ones above: os-Run.salam