Package exec

import "os/exec"
Overview
Index
Examples

Overview ▾

包exec运行外部命令. 它包装了os.StartProcess,以便更轻松地重新映射stdin和stdout,将I / O与管道连接以及进行其他调整.

与C和其他语言的"系统"库调用不同,os / exec软件包有意不调用系统外壳程序,也不扩展任何glob模式或处理外壳程序通常完成的其他扩展,管道或重定向. 程序包的行为更像C的" exec"函数系列. 要扩展glob模式,请直接调用外壳程序,注意避免任何危险的输入,或者使用path / filepath包的Glob函数. 要扩展环境变量,请使用程序包的ExpandEnv.

请注意,此软件包中的示例假定使用Unix系统. 它们可能无法在Windows上运行,也不能在golang.org和godoc.org使用的Go Playground中运行.

Variables

如果路径搜索未能找到可执行文件,则会导致ErrNotFound错误.

var ErrNotFound = errors.New("executable file not found in $PATH")

func LookPath

func LookPath(file string) (string, error)

LookPath在PATH环境变量命名的目录中搜索可执行文件(名为可执行文件). 如果文件包含斜杠,则直接尝试,不查询PATH. 结果可能是绝对路径或相对于当前目录的路径.

Example

type Cmd

Cmd表示正在准备或运行的外部命令.

调用Cmd的Run,Output或CombinedOutput方法后,将无法重用该Cmd.

type Cmd struct {
    // Path is the path of the command to run.
    //
    // This is the only field that must be set to a non-zero
    // value. If Path is relative, it is evaluated relative
    // to Dir.
    Path string

    // Args holds command line arguments, including the command as Args[0].
    // If the Args field is empty or nil, Run uses {Path}.
    //
    // In typical use, both Path and Args are set by calling Command.
    Args []string

    // Env specifies the environment of the process.
    // Each entry is of the form "key=value".
    // If Env is nil, the new process uses the current process's
    // environment.
    // If Env contains duplicate environment keys, only the last
    // value in the slice for each duplicate key is used.
    // As a special case on Windows, SYSTEMROOT is always added if
    // missing and not explicitly set to the empty string.
    Env []string

    // Dir specifies the working directory of the command.
    // If Dir is the empty string, Run runs the command in the
    // calling process's current directory.
    Dir string

    // Stdin specifies the process's standard input.
    //
    // If Stdin is nil, the process reads from the null device (os.DevNull).
    //
    // If Stdin is an *os.File, the process's standard input is connected
    // directly to that file.
    //
    // Otherwise, during the execution of the command a separate
    // goroutine reads from Stdin and delivers that data to the command
    // over a pipe. In this case, Wait does not complete until the goroutine
    // stops copying, either because it has reached the end of Stdin
    // (EOF or a read error) or because writing to the pipe returned an error.
    Stdin io.Reader

    // Stdout and Stderr specify the process's standard output and error.
    //
    // If either is nil, Run connects the corresponding file descriptor
    // to the null device (os.DevNull).
    //
    // If either is an *os.File, the corresponding output from the process
    // is connected directly to that file.
    //
    // Otherwise, during the execution of the command a separate goroutine
    // reads from the process over a pipe and delivers that data to the
    // corresponding Writer. In this case, Wait does not complete until the
    // goroutine reaches EOF or encounters an error.
    //
    // If Stdout and Stderr are the same writer, and have a type that can
    // be compared with ==, at most one goroutine at a time will call Write.
    Stdout io.Writer
    Stderr io.Writer

    // ExtraFiles specifies additional open files to be inherited by the
    // new process. It does not include standard input, standard output, or
    // standard error. If non-nil, entry i becomes file descriptor 3+i.
    //
    // ExtraFiles is not supported on Windows.
    ExtraFiles []*os.File

    // SysProcAttr holds optional, operating system-specific attributes.
    // Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
    SysProcAttr *syscall.SysProcAttr

    // Process is the underlying process, once started.
    Process *os.Process

    // ProcessState contains information about an exited process,
    // available after a call to Wait or Run.
    ProcessState *os.ProcessState
    // contains filtered or unexported fields
}

func Command

func Command(name string, arg ...string) *Cmd

命令返回Cmd结构以给定参数执行命名程序.

它仅在返回的结构中设置Path和Args.

如果名称不包含路径分隔符,则Command会使用LookPath将名称解析为完整路径(如果可能). 否则,它将名称直接用作路径.

返回的Cmd的Args字段由命令名称后跟arg的元素构成,因此arg不应包括命令名称本身. 例如,Command(" echo"," hello"). Args [0]始终是名称,而不是可能解析的Path.

在Windows上,进程将整个命令行作为单个字符串接收并进行自己的解析. Command使用与CommandLineToArgvW(这是最常见的方法)兼容的应用程序兼容的算法,将Args组合并加引为命令行字符串. 值得注意的例外是msiexec.exe和cmd.exe(以及所有批处理文件),它们具有不同的取消引用算法. 在这些或其他类似情况下,您可以自己报价,并在SysProcAttr.CmdLine中提供完整的命令行,而使Args为空.

Example

示例(环境)

func CommandContext 1.7

func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

CommandContext类似于Command,但包含上下文.

如果上下文在命令自行完成之前完成,则提供的上下文用于终止进程(通过调用os.Process.Kill).

Example

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput运行命令并返回其组合的标准输出和标准错误.

Example

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

输出运行命令并返回其标准输出. 返回的任何错误通常都是* ExitError类型. 如果c.Stderr为零,则Output填充ExitError.Stderr.

Example

func (*Cmd) Run

func (c *Cmd) Run() error

运行将启动指定的命令并等待其完成.

如果命令运行,则返回错误nil,复制stdin,stdout和stderr时没有问题,并且退出状态为零.

如果命令启动但未成功完成,则错误的类型为* ExitError. 对于其他情况,可能会返回其他错误类型.

如果调用goroutine已使用runtime.LockOSThread锁定了操作系统线程并修改了任何可继承的OS级线程状态(例如Linux或Plan 9名称空间),则新进程将继承调用者的线程状态.

Example

func (*Cmd) Start

func (c *Cmd) Start() error

启动将启动指定的命令,但不等待其完成.

一旦命令退出,Wait方法将返回退出代码并释放关联的资源.

Example

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

当命令启动时,StderrPipe返回将连接到命令的标准错误的管道.

在看到命令退出后,Wait将关闭管道,因此大多数调用者都不需要自己关闭管道;而是将其关闭. 但是,这意味着在完成对管道的所有读取之前调用Wait是不正确的. 出于相同的原因,使用StderrPipe时使用"运行"是不正确的. 请参阅StdoutPipe示例以了解惯用用法.

Example

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts. The pipe will be closed automatically after Wait sees the command exit. A caller need only call Close to force the pipe to close sooner. For example, if the command being run will not exit until standard input is closed, the caller must close the pipe.

Example

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe返回一个管道,该管道将在命令启动时连接到命令的标准输出.

在看到命令退出后,Wait将关闭管道,因此大多数调用者都不需要自己关闭管道;而是将其关闭. 但是,这意味着在完成对管道的所有读取之前调用Wait是不正确的. 出于同样的原因,使用StdoutPipe时调用Run是不正确的. 请参阅示例以了解惯用用法.

Example

func (*Cmd) String 1.13

func (c *Cmd) String() string

字符串返回人类可读的c描述. 它仅用于调试. 特别是,它不适合用作外壳的输入. 在Go发行版中,String的输出可能会有所不同.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait等待命令退出,并等待所有复制到stdin或从stdout或stderr复制完成.

该命令必须已经由"启动"启动.

如果命令运行,则返回错误nil,复制stdin,stdout和stderr时没有问题,并且退出状态为零.

如果命令运行失败或未成功完成,则错误的类型为* ExitError. 对于I / O问题,可能会返回其他错误类型.

如果c.Stdin,c.Stdout或c.Stderr中的任何一个都不是* os.File,则Wait也将等待相应的I / O循环复制到该进程或从该进程复制完成.

等待释放与Cmd关联的所有资源.

type Error

当LookPath无法将文件归类为可执行文件时,将返回错误.

type Error struct {
    // Name is the file name for which the error occurred.
    Name string
    // Err is the underlying error.
    Err error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap 1.13

func (e *Error) Unwrap() error

type ExitError

ExitError通过命令报告退出失败.

type ExitError struct {
    *os.ProcessState

    // Stderr holds a subset of the standard error output from the
    // Cmd.Output method if standard error was not otherwise being
    // collected.
    //
    // If the error output is long, Stderr may contain only a prefix
    // and suffix of the output, with the middle replaced with
    // text about the number of omitted bytes.
    //
    // Stderr is provided for debugging, for inclusion in error messages.
    // Users with other needs should redirect Cmd.Stderr as needed.
    Stderr []byte // Go 1.6
}

func (*ExitError) Error

func (e *ExitError) Error() string

by  ICOPY.SITE