Source Edit

This module implements an advanced facility for executing OS processes and process communication.

See also:

Imports

strutils, os, strtabs, streams, cpuinfo, streamwrapper, since, winlean

Types

  1. Process = ref ProcessObj

Represents an operating system process. Source Edit

  1. ProcessOption = enum
  2. poEchoCmd, ## Echo the command before execution.
  3. poUsePath, ## Asks system to search for executable using PATH environment
  4. ## variable.
  5. ## On Windows, this is the default.
  6. poEvalCommand, ## Pass `command` directly to the shell, without quoting.
  7. ## Use it only if `command` comes from trusted source.
  8. poStdErrToStdOut, ## Merge stdout and stderr to the stdout stream.
  9. poParentStreams, ## Use the parent's streams.
  10. poInteractive, ## Optimize the buffer handling for responsiveness for
  11. ## UI applications. Currently this only affects
  12. ## Windows: Named pipes are used so that you can peek
  13. ## at the process' output streams.
  14. poDaemon ## Windows: The program creates no Window.
  15. ## Unix: Start the program as a daemon. This is still
  16. ## work in progress!

Options that can be passed to startProcess proc. Source Edit

Procs

  1. proc close(p: Process) {....gcsafe, extern: "nosp$1", raises: [IOError, OSError],
  2. tags: [WriteIOEffect], forbids: [].}

When the process has finished executing, cleanup related handles.

Warning: If the process has not finished executing, this will forcibly terminate the process. Doing so may result in zombie processes and pty leaks.

Source Edit

  1. proc countProcessors(): int {....gcsafe, extern: "nosp$1", raises: [], tags: [],
  2. forbids: [].}

Returns the number of the processors/cores the machine has. Returns 0 if it cannot be detected. It is implemented just calling cpuinfo.countProcessors. Source Edit

  1. proc errorHandle(p: Process): FileHandle {....gcsafe, extern: "nosp$1", raises: [],
  2. tags: [], forbids: [].}

Returns p’s error file handle for reading from.

Warning: The returned FileHandle should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc errorStream(p: Process): Stream {....gcsafe, extern: "nosp$1", tags: [],
  2. raises: [], forbids: [].}

Returns p’s error stream for reading from.

You cannot perform peek/write/setOption operations to this stream. Use peekableErrorStream proc if you need to peek stream.

Warning: The returned Stream should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc execCmd(command: string): int {....gcsafe, extern: "nosp$1", tags: [
  2. ExecIOEffect, ReadIOEffect, RootEffect], raises: [OSError], forbids: [].}

Executes command and returns its error code.

Standard input, output, error streams are inherited from the calling process. This operation is also often called system.

See also:

Example:

  1. let errC = execCmd("nim c -r mytestfile.nim")

Source Edit

  1. proc execCmdEx(command: string;
  2. options: set[ProcessOption] = {poStdErrToStdOut, poUsePath};
  3. env: StringTableRef = nil; workingDir = ""; input = ""): tuple[
  4. output: string, exitCode: int] {....raises: [OSError, IOError], tags: [
  5. ExecIOEffect, ReadIOEffect, RootEffect], gcsafe, forbids: [].}

A convenience proc that runs the command, and returns its output and exitCode. env and workingDir params behave as for startProcess. If input.len > 0, it is passed as stdin.

Note: this could block if input.len is greater than your OS’s maximum pipe buffer size.

See also:

Example:

  1. var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
  2. import std/[strutils, strtabs]
  3. stripLineEnd(result[0]) ## portable way to remove trailing newline, if any
  4. doAssert result == ("12", 0)
  5. doAssert execCmdEx("ls --nonexistent").exitCode != 0
  6. when defined(posix):
  7. assert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
  8. assert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)

Source Edit

  1. proc execProcess(command: string; workingDir: string = "";
  2. args: openArray[string] = []; env: StringTableRef = nil;
  3. options: set[ProcessOption] = {poStdErrToStdOut, poUsePath, poEvalCommand}): string {.
  4. ...gcsafe, extern: "nosp$1", raises: [OSError, IOError],
  5. tags: [ExecIOEffect, ReadIOEffect, RootEffect], forbids: [].}

A convenience procedure that executes command with startProcess and returns its output as a string.

Warning: This function uses poEvalCommand by default for backwards compatibility. Make sure to pass options explicitly.

See also:

Example:

  1. let outp = execProcess("nim", args=["c", "-r", "mytestfile.nim"], options={poUsePath})
  2. let outp_shell = execProcess("nim c -r mytestfile.nim")
  3. # Note: outp may have an interleave of text from the nim compile
  4. # and any output from mytestfile when it runs

Source Edit

  1. proc execProcesses(cmds: openArray[string];
  2. options = {poStdErrToStdOut, poParentStreams};
  3. n = countProcessors(); beforeRunEvent: proc (idx: int) = nil;
  4. afterRunEvent: proc (idx: int; p: Process) = nil): int {.
  5. ...gcsafe, extern: "nosp$1", raises: [ValueError, OSError, IOError],
  6. tags: [ExecIOEffect, TimeEffect, ReadEnvEffect, RootEffect],
  7. effectsOf: [beforeRunEvent, afterRunEvent], ...forbids: [].}

Executes the commands cmds in parallel. Creates n processes that execute in parallel.

The highest (absolute) return value of all processes is returned. Runs beforeRunEvent before running each command.

Source Edit

  1. proc hasData(p: Process): bool {....raises: [], tags: [], forbids: [].}

Source Edit

  1. proc inputHandle(p: Process): FileHandle {....gcsafe, raises: [], extern: "nosp$1",
  2. tags: [], forbids: [].}

Returns p’s input file handle for writing to.

Warning: The returned FileHandle should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc inputStream(p: Process): Stream {....gcsafe, extern: "nosp$1", tags: [],
  2. raises: [], forbids: [].}

Returns p’s input stream for writing to.

Warning: The returned Stream should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc kill(p: Process) {....gcsafe, extern: "nosp$1", tags: [], raises: [OSError],
  2. forbids: [].}

Kill the process p.

On Posix OSes the procedure sends SIGKILL to the process. On Windows kill is simply an alias for terminate().

See also:

Source Edit

  1. proc outputHandle(p: Process): FileHandle {....gcsafe, extern: "nosp$1",
  2. raises: [], tags: [], forbids: [].}

Returns p’s output file handle for reading from.

Warning: The returned FileHandle should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc outputStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
  2. raises: [IOError, OSError], tags: [],
  3. forbids: [].}

Returns p’s output stream for reading from.

You cannot perform peek/write/setOption operations to this stream. Use peekableOutputStream proc if you need to peek stream.

Warning: The returned Stream should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc peekableErrorStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
  2. tags: [], raises: [], forbids: [].}

Returns p’s error stream for reading from.

You can run peek operation to returned stream.

Warning: The returned Stream should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc peekableOutputStream(p: Process): Stream {....gcsafe, extern: "nosp$1",
  2. tags: [], raises: [], forbids: [].}

Returns p’s output stream for reading from.

You can peek returned stream.

Warning: The returned Stream should not be closed manually as it is closed when closing the Process p.

See also:

Source Edit

  1. proc peekExitCode(p: Process): int {....gcsafe, extern: "nosp$1",
  2. raises: [OSError], tags: [], forbids: [].}

Return -1 if the process is still running. Otherwise the process’ exit code.

On posix, if the process has exited because of a signal, 128 + signal number will be returned.

Source Edit

  1. proc processID(p: Process): int {....gcsafe, extern: "nosp$1", raises: [],
  2. tags: [], forbids: [].}

Returns p’s process ID.

See also:

Source Edit

  1. proc readLines(p: Process): (seq[string], int) {.
  2. ...raises: [OSError, IOError, ValueError], tags: [ReadIOEffect], forbids: [].}

Convenience function for working with startProcess to read data from a background process.

See also:

Example:

  1. const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  2. var ps: seq[Process]
  3. for prog in ["a", "b"]: # run 2 progs in parallel
  4. ps.add startProcess("nim", "", ["r", prog], nil, opts)
  5. for p in ps:
  6. let (lines, exCode) = p.readLines
  7. if exCode != 0:
  8. for line in lines: echo line
  9. p.close

Source Edit

  1. proc resume(p: Process) {....gcsafe, extern: "nosp$1", tags: [], raises: [],
  2. forbids: [].}

Resumes the process p.

See also:

Source Edit

  1. proc running(p: Process): bool {....gcsafe, extern: "nosp$1", raises: [OSError],
  2. tags: [], forbids: [].}

Returns true if the process p is still running. Returns immediately. Source Edit

  1. proc startProcess(command: string; workingDir: string = "";
  2. args: openArray[string] = []; env: StringTableRef = nil;
  3. options: set[ProcessOption] = {poStdErrToStdOut}): owned(
  4. Process) {....gcsafe, extern: "nosp$1", raises: [OSError, IOError],
  5. tags: [ExecIOEffect, ReadEnvEffect, RootEffect], forbids: [].}

Starts a process. Command is the executable file, workingDir is the process’s working directory. If workingDir == “” the current directory is used (default). args are the command line arguments that are passed to the process. On many operating systems, the first command line argument is the name of the executable. args should not contain this argument! env is the environment that will be passed to the process. If env == nil (default) the environment is inherited of the parent process. options are additional flags that may be passed to startProcess. See the documentation of ProcessOption for the meaning of these flags.

You need to close the process when done.

Note that you can’t pass any args if you use the option poEvalCommand, which invokes the system shell to run the specified command. In this situation you have to concatenate manually the contents of args to command carefully escaping/quoting any special characters, since it will be passed as is to the system shell. Each system/shell may feature different escaping rules, so try to avoid this kind of shell invocation if possible as it leads to non portable software.

Return value: The newly created process object. Nil is never returned, but OSError is raised in case of an error.

See also:

Source Edit

  1. proc suspend(p: Process) {....gcsafe, extern: "nosp$1", tags: [], raises: [],
  2. forbids: [].}

Suspends the process p.

See also:

Source Edit

  1. proc terminate(p: Process) {....gcsafe, extern: "nosp$1", tags: [],
  2. raises: [OSError], forbids: [].}

Stop the process p.

On Posix OSes the procedure sends SIGTERM to the process. On Windows the Win32 API function TerminateProcess() is called to stop the process.

See also:

Source Edit

  1. proc waitForExit(p: Process; timeout: int = -1): int {....gcsafe, extern: "nosp$1",
  2. raises: [OSError, ValueError], tags: [], forbids: [].}

Waits for the process to finish and returns p’s error code.

Warning: Be careful when using waitForExit for processes created without poParentStreams because they may fill output buffers, causing deadlock.

On posix, if the process has exited because of a signal, 128 + signal number will be returned.

Warning: When working with timeout parameters, remember that the value is typically expressed in milliseconds, and ensure that the correct unit of time is used to avoid unexpected behavior.

Source Edit

Iterators

  1. iterator lines(p: Process; keepNewLines = false): string {.
  2. ...raises: [OSError, IOError, ValueError], tags: [ReadIOEffect], forbids: [].}

Convenience iterator for working with startProcess to read data from a background process.

See also:

Example:

  1. const opts = {poUsePath, poDaemon, poStdErrToStdOut}
  2. var ps: seq[Process]
  3. for prog in ["a", "b"]: # run 2 progs in parallel
  4. ps.add startProcess("nim", "", ["r", prog], nil, opts)
  5. for p in ps:
  6. var i = 0
  7. for line in p.lines:
  8. echo line
  9. i.inc
  10. if i > 100: break
  11. p.close

Source Edit

Exports

quoteShell, quoteShellWindows, quoteShellPosix