Running other programs, talking to them through pipes, reading with a time limit, telling an exit code from a signal, and stopping them.
import os.process
The os.process package runs another program directly, with no shell in between. The program's path and its arguments are given separately, so nothing has to be quoted and spaces or special characters in an argument cause no trouble. Use it to call tools such as git, ffmpeg or a compiler with file names that came from a user. For a quick one-line shell command use os (Run, RunCapture) or os.shell; when a program cannot start at all, the reason is recorded in os.error.
A run has up to four steps: Start or StartCaptured launches the program and returns at once, Wait blocks until it exits and returns the exit code, ReadStdout and ReadStderr read what a captured run printed, and Cleanup deletes the two temporary files that held it. A captured program gets an empty standard input.
For a program you talk to while it runs, with pipes, time limits and exit codes or signals, use Command, Launch and Child, described in the sections below. For a program that must see a terminal, use os.pty.
What people get wrong:
•
Treating IsRunning as a live check. It reports a flag that Start sets and only Wait, Kill or Terminate clear; it stays true after the program has exited on its own.
•
Killing without waiting. Kill and Terminate only send the signal. Call Wait afterwards, or the finished process stays in the process table as a zombie.
•
Expecting a timeout from Wait. Wait on a Process waits as long as the program runs. To give up after a while use a Child (see below), whose Wait takes a time limit.
•
Forgetting Cleanup. Each captured run leaves two files in the temporary folder until you call it.
On Windows the arguments are joined into one command line with quotes around those that contain spaces, and the ANSI CreateProcessA starts the program. An argument that itself contains a ", or text outside the system code page such as Persian, does not arrive intact there; Fork and WaitPid return -1.
Pass arguments exactly as they are
Each element of the argument vector reaches the program as one argument, byte for byte. Spaces, quotes, a $ or a ; mean nothing special, because no shell reads them. That makes this package the safe way to pass file names and other text that came from a user.
The program name is looked up on the PATH like in a terminal, so printf works without a full path. The vector does not include the program name itself; the package adds it. This exactness holds on Linux and macOS; see the note above for Windows.
Exit code, output and error output
A program reports success with exit code zero and anything else on failure, and it writes its complaints to the error output. After Wait, read both: ReadStdout for the results and ReadStderr for the reason it failed. Call Cleanup after reading, because the captured output is kept in temporary files until then.
os-process-guide-exitcode.salam
import os.process
funcmain:
mut args := Vector {} asVector<str>
defer args.Free()
args.Push("-c")
args.Push("echo copying files; echo disk is full >&2; exit 3")
mut p := process.StartCaptured("sh", args)
code := process.Wait(p)
out := process.ReadStdout(p).Trim()
err := process.ReadStderr(p).Trim()
process.Cleanup(p)
println"output:", out
if code != 0:
println"failed with code", code, "and said:", err
ret0endprintln"all good"end
Output
output: copying files
failed with code 3 and said: disk is full
Run several programs at once
StartCaptured returns as soon as the program has started, so you can start several and wait for them afterwards. The total time is about that of the slowest one rather than the sum of all. Waiting in the order you started them keeps the output in a fixed order, even when a later job finished first.
started 3 jobs
0 thumbnails done
0 search index done
0 sitemap done
Keep the number of programs you run at once reasonable; os.platform's CpuCount is a good limit for work that keeps the processor busy.
A helper that runs a program and returns its output
Most programs need the same few lines every time: start, check that it started, wait, read, clean up. Put them in one function. A defer right after the start makes sure Cleanup runs on every way out of the function, and an out-parameter tells the caller whether the program succeeded.
os-process-guide-helper.salam
import os.error
import os.process
funccapture(program: str, args: Vector<str>, ok &: bool): str:
error.Clear()
mut p := process.StartCaptured(program, args)
if error.HasError():
ok = falseret""enddefer process.Cleanup(p)
ok = process.Wait(p) == 0ret process.ReadStdout(p)
endfuncmain:
mut args := Vector {} asVector<str>
defer args.Free()
args.Push("-c")
args.Push("printf 'pear\\napple\\nfig\\n' | sort")
mut ok := false
out := capture("sh", args, ok)
println"worked:", ok
print out
capture("/no/such/tool", args, ok)
println"missing tool worked:", ok
end
Output
worked: true
apple
fig
pear
missing tool worked: false
Stop a program
Terminate sends SIGTERM, which a well-behaved program catches to save its work and exit; Kill sends SIGKILL, which cannot be caught. Either way, Wait collects the program afterwards. A program ended by a signal reports 128 plus the signal number as its exit code, so 143 means SIGTERM and 137 means SIGKILL, the same numbers a shell shows.
started, running: true
stopped with exit code 143 = 128 + signal 15
running: false
Talk to a running child
Start and StartCaptured run a program to the end. When you need to talk to it while it runs, describe it with a Command (NewCommand gives one for a program), pass it to Launch, and use the Child it returns. Set stdin_mode, stdout_mode and stderr_mode to Pipe (or call Piped) to connect a stream to your program, to Null to throw it away, or leave Inherit to share your own. Merge on the error stream puts it into the output pipe in the order it was written. Arg, Env, Unset and the cwd and clear_env fields set the arguments, the environment and the folder. Writing to a child that has already gone returns false and never kills your program.
Every read takes a time in milliseconds: 0 only looks, a positive number waits that long, a negative number waits for ever. ReadAvailable returns whatever has arrived, ReadLine one complete line, Read an exact number of bytes, ReadUntil everything up to a given text (the way to wait for a prompt) and ReadFor everything that arrives in a period. A read returns a Chunk: check timed_out (nothing came, and the child may still be working) and eof (the stream ended) before using data, and Free it. Bytes that were read but not yet returned stay in the child, so a timed-out call loses nothing. The ReadErr methods do the same for the error pipe, and ReadBytes reads binary data into a buffer.
line: first
nothing yet: true
line: second
closed: true
Exit code or signal
Child.Wait takes a time limit and returns a Status. A child that ended by itself has exited set and its code in code; one that a signal ended has signaled set and the number in signal. This differs from Process.Wait, which folds a signal into 128 plus the number. ReturnCode gives the Python-style number (the code, or the negative signal), and Success is true for code 0. When the limit passes first, timed_out is set and the child keeps running; Poll asks whether it is still running without waiting.
os-process-guide-status.salam
import os.process
funcdescribe(script: str):
mut cmd := process.NewCommand("sh")
cmd.Arg("-c")
cmd.Arg(script)
mut child := process.Launch(cmd)
st := child.Wait(2000)
if st.exited:
println"exited with code", st.code
else st.signaled:
println"killed by signal", st.signal
end
child.Close()
cmd.Free()
endfuncmain:
describe("exit 3")
describe("kill -TERM $$")
describe("kill -KILL $$")
end
Output
exited with code 3
killed by signal 15
killed by signal 9
Run with a timeout
RunTimeout is the one-call version: it writes the input text, collects the whole output and error output, and kills the child when the time runs out. It reads both pipes while it writes, so a child that prints a megabyte on each stream cannot deadlock it. RunCommand does the same for a Command with an environment or folder. The result is a RunResult: started, status, stdout, stderr and timed_out; call Free on it.
Kill a shell and the programs it started keep running. Start the child with new_group and KillGroup (or SignalGroup with any signal) stops the whole group. RunTimeout does this for you. Signal, Kill and Terminate reach only the child itself.
On Unix a program that cannot be found, or a folder that cannot be entered, makes Launch return a child whose ok is false and whose error says why; the check happens before Launch returns, so there is no need to wait for an exit code 127.
On Windows Launch uses CreateProcessW and anonymous pipes. Every signal ends the child at once and is reported as a signal, RunCommand writes all of its input before it starts reading, and the pseudo terminal of os.pty is not available. The tests that start real children run on Linux and macOS.
Need
Use
Run a program and see its output on the screen
Start, then Wait
Run a program and use its output
StartCaptured, Wait, ReadStdout, Cleanup
Stop a program politely, or at once
Terminate, Kill
Pipes or redirection
run sh with -c and a script, as in the examples above
How to start a child: the program, its arguments, folder, environment and what to do with its three streams. Fill it in, pass it to Launch, and call Free when done.
Name
Type
Description
program
str = ""
The program to run. A name without a slash is searched on PATH.
args
Vector<str>
The arguments, not including the program name. Each reaches the child as one argument.
cwd
str = ""
The folder to run in. Empty means your own current folder.
env
HashMap<str, str>
Variables to add to the child's environment, replacing any with the same name.
unset_env
Vector<str>
Names of variables to remove from the child's environment.
clear_env
bool = false
When true the child starts with an empty environment plus only the variables in env.
stdin_mode
int = 0
What to do with the child's input: Inherit, Pipe or Null.
stdout_mode
int = 0
What to do with the child's output: Inherit, Pipe or Null.
stderr_mode
int = 0
What to do with the child's error output: Inherit, Pipe, Null or Merge.
new_group
bool = false
Starts the child in its own process group, so KillGroup can stop it together with everything it started. Unix only; on Windows it adds a new console process group.
What a read returns: the text, how many bytes it holds, and whether the stream ended or nothing came in time.
Name
Type
Description
data
str = ""
The text read, as a string that stops at the first zero byte. Use len for the real byte count. Empty (but still yours to free) on a timeout or at the end.
len
int = 0
The number of bytes read. For a line it excludes the line ending.
eof
bool = false
True when the stream has ended and no more data will come.
timed_out
bool = false
True when nothing arrived within the time allowed. Whatever was partly read stays buffered for the next call.
Reads one line, without its line ending, waiting up to ms milliseconds for it to be complete. At the end of the stream it returns what is left with eof set.
Waits up to ms milliseconds for the child to end and returns its Status. On a timeout the status has timed_out set and the child keeps running. 0 only checks; a negative number waits for ever. A finished child returns the same status every time.
Runs a command to the end: writes the text to its input, collects all of its output and error output without ever blocking on a full pipe, and kills it when timeout_ms passes. A negative time means no limit.
Runs a program with the given arguments and input text, collects its output and error output, and kills it, and everything it started, when the time in milliseconds runs out. The result tells whether it timed out.
Asks the system for permission and starts a program as root or administrator, without waiting for it to end: an administrator prompt on macOS, pkexec on Linux and the UAC dialog on Windows. Returns an empty string on success, otherwise the reason.
Runs a program with its arguments and does not wait; its output goes straight to your own program's output. The name is searched on PATH. When it cannot start, pid is 0 and os.error holds ProcessFailed.
Waits for the process to finish and returns its exit code: 128 plus the signal number when a signal ended it, -1 when it never started. There is no timeout.
Splits the current process in two: it returns zero in the child and the child's id in the parent. On Unix systems only; its example is not run here.
os-process-Fork.salam
import os.process
funcmain:
pid := process.Fork()
if pid == 0:
println"I am the child"
process.ExitNow(0)
end
process.WaitPid(pid)
println"the child has finished"end