?
? ????? PHP ??? ???? ??? ?? ??
import "os/exec"
Overview
Index
Examples
包 exec 執(zhí)行外部命令。它包裝了 os.StartProcess ,以便重新映射 stdin 和 stdout ,使用管道連接 I/O 并進(jìn)行其他調(diào)整。
與來自 C 和其他語言的“系統(tǒng)”庫調(diào)用不同,os/exec 包有意不調(diào)用系統(tǒng)shell,并且不會擴(kuò)展任何 glob 模式或處理通常由 shell 執(zhí)行的其他擴(kuò)展,管道或重定向。該軟件包的行為更像 C 的 “exec” 系列功能。要擴(kuò)展 glob 模式,請直接調(diào)用外殼,注意避開任何危險(xiǎn)輸入,或者使用 path/filepath 包的 Glob 函數(shù)。要擴(kuò)展環(huán)境變量,請使用 package os 的 ExpandEnv 。
請注意,此包中的示例假定為Unix系統(tǒng)。它們可能無法在Windows上運(yùn)行,并且它們不會在golang.org和godoc.org使用的Go Playground中運(yùn)行。
Variables
func LookPath(file string) (string, error)
type Cmd
func Command(name string, arg ...string) *Cmd
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd
func (c *Cmd) CombinedOutput() ([]byte, error)
func (c *Cmd) Output() ([]byte, error)
func (c *Cmd) Run() error
func (c *Cmd) Start() error
func (c *Cmd) StderrPipe() (io.ReadCloser, error)
func (c *Cmd) StdinPipe() (io.WriteCloser, error)
func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
func (c *Cmd) Wait() error
type Error
func (e *Error) Error() string
type ExitError
func (e *ExitError) Error() string
Cmd.CombinedOutput Cmd.Output Cmd.Run Cmd.Start Cmd.StderrPipe Cmd.StdinPipe Cmd.StdoutPipe Command CommandContext Command (Environment) LookPath
exec.go exec_unix.go lp_unix.go
ErrNotFound 是如果路徑搜索未能找到可執(zhí)行文件導(dǎo)致的錯(cuò)誤。
var ErrNotFound = errors.New("executable file not found in $PATH")
func LookPath(file string) (string, error)
LookPath 在由 PATH 環(huán)境變量命名的目錄中搜索名為 file 的可執(zhí)行二進(jìn)制文件。如果文件包含斜線,則直接嘗試并且不會咨詢 PATH 。結(jié)果可能是相對于當(dāng)前目錄的絕對路徑或路徑。
package mainimport ("fmt""log""os/exec")func main() { path, err := exec.LookPath("fortune")if err != nil { log.Fatal("installing fortune is in your future")} fmt.Printf("fortune is available at %s\n", path)}
Cmd 代表正在準(zhǔn)備或運(yùn)行的外部命令。
調(diào)用它的 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. 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 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 []*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(name string, arg ...string) *Cmd
命令返回 Cmd 結(jié)構(gòu)來執(zhí)行具有給定參數(shù)的命名程序。
它僅在返回的結(jié)構(gòu)中設(shè)置 Path 和 Args 。
如果名稱不包含路徑分隔符,Command 將盡可能使用 LookPath 將名稱解析為完整路徑。否則,它直接使用名稱作為路徑。
返回的 Cmd 的 Args 字段由命令名稱和后面的 arg 元素構(gòu)成,所以 arg 不應(yīng)包含命令名稱本身。例如,Command(“echo”,“hello”)。Args0 始終是名稱,而不是可能解析的路徑。
package mainimport ("bytes""fmt""log""os/exec""strings")func main() { cmd := exec.Command("tr", "a-z", "A-Z") cmd.Stdin = strings.NewReader("some input")var out bytes.Buffer cmd.Stdout = &out err := cmd.Run()if err != nil { log.Fatal(err)} fmt.Printf("in all caps: %q\n", out.String())}
package mainimport ("log""os""os/exec")func main() { cmd := exec.Command("prog") cmd.Env = append(os.Environ(),"FOO=duplicate_value", // ignored"FOO=actual_value", // this value is used)if err := cmd.Run(); err != nil { log.Fatal(err)}}
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd
CommandContext 與 Command 相似,但包含一個(gè)上下文。
如果上下文在命令完成之前完成,則提供的上下文用于終止進(jìn)程(通過調(diào)用 os.Process.Kill )。
package mainimport ("context""os/exec""time")func main() { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel()if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {// This will fail after 100 milliseconds. The 5 second sleep// will be interrupted.}}
func (c *Cmd) CombinedOutput() ([]byte, error)
CombinedOutput 運(yùn)行該命令并返回其組合標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤。
package mainimport ("fmt""log""os/exec")func main() { cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stdoutStderr, err := cmd.CombinedOutput()if err != nil { log.Fatal(err)} fmt.Printf("%s\n", stdoutStderr)}
func (c *Cmd) Output() ([]byte, error)
輸出運(yùn)行該命令并返回其標(biāo)準(zhǔn)輸出。任何返回的錯(cuò)誤通常都是 * ExitError 類型。如果 c.Stderr 為零,則輸出填充 ExitError.Stderr 。
package mainimport ("fmt""log""os/exec")func main() { out, err := exec.Command("date").Output()if err != nil { log.Fatal(err)} fmt.Printf("The date is %s\n", out)}
func (c *Cmd) Run() error
運(yùn)行開始指定的命令并等待它完成。
如果命令運(yùn)行,則返回的錯(cuò)誤為零,在復(fù)制 stdin,stdout 和 stderr 時(shí)沒有問題,并以零退出狀態(tài)退出。
如果該命令啟動但未成功完成,則錯(cuò)誤類型為 * ExitError 。其他錯(cuò)誤類型可能會返回其他情況。
package mainimport ("log""os/exec")func main() { cmd := exec.Command("sleep", "1") log.Printf("Running command and waiting for it to finish...") err := cmd.Run() log.Printf("Command finished with error: %v", err)}
func (c *Cmd) Start() error
開始啟動指定的命令,但不等待它完成。
一旦命令退出,Wait 方法將返回退出代碼并釋放相關(guān)資源。
package mainimport ("log""os/exec")func main() { cmd := exec.Command("sleep", "5") err := cmd.Start()if err != nil { log.Fatal(err)} log.Printf("Waiting for command to finish...") err = cmd.Wait() log.Printf("Command finished with error: %v", err)}
func (c *Cmd) StderrPipe() (io.ReadCloser, error)
當(dāng)命令啟動時(shí),StderrPipe 將返回一個(gè)將連接到命令標(biāo)準(zhǔn)錯(cuò)誤的管道。
等待會在看到命令退出后關(guān)閉管道,因此大多數(shù)呼叫者不需要關(guān)閉管道; 但是,含義是在從管道讀取完成之前調(diào)用 Wait 是不正確的。出于同樣的原因,在使用 StderrPipe 時(shí)使用 Run 是不正確的。查看 StdoutPipe 示例了解慣用用法。
package mainimport ("fmt""io/ioutil""log""os/exec")func main() { cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr") stderr, err := cmd.StderrPipe()if err != nil { log.Fatal(err)}if err := cmd.Start(); err != nil { log.Fatal(err)} slurp, _ := ioutil.ReadAll(stderr) fmt.Printf("%s\n", slurp)if err := cmd.Wait(); err != nil { log.Fatal(err)}}
func (c *Cmd) StdinPipe() (io.WriteCloser, error)
當(dāng)命令啟動時(shí),StdinPipe 返回一個(gè)將連接到命令標(biāo)準(zhǔn)輸入的管道。在 Wait 看到命令退出后,管道將自動關(guān)閉。呼叫者只需調(diào)用 Close 即可更快地關(guān)閉管道。例如,如果正在運(yùn)行的命令在標(biāo)準(zhǔn)輸入關(guān)閉之前不會退出,則調(diào)用者必須關(guān)閉管道。
package mainimport ("fmt""io""log""os/exec")func main() { cmd := exec.Command("cat") stdin, err := cmd.StdinPipe()if err != nil { log.Fatal(err)} go func() { defer stdin.Close() io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")}() out, err := cmd.CombinedOutput()if err != nil { log.Fatal(err)} fmt.Printf("%s\n", out)}
func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
當(dāng)命令啟動時(shí),StdoutPipe 返回一個(gè)將連接到命令標(biāo)準(zhǔn)輸出的管道。
等待會在看到命令退出后關(guān)閉管道,因此大多數(shù)呼叫者不需要關(guān)閉管道; 但是,含義是在從管道讀取完成之前調(diào)用 Wait 是不正確的。出于同樣的原因,使用 StdoutPipe 時(shí)調(diào)用 Run 是不正確的。查看習(xí)慣用法的例子。
package mainimport ("encoding/json""fmt""log""os/exec")func main() { cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`) stdout, err := cmd.StdoutPipe()if err != nil { log.Fatal(err)}if err := cmd.Start(); err != nil { log.Fatal(err)}var person struct { Name string Age int}if err := json.NewDecoder(stdout).Decode(&person); err != nil { log.Fatal(err)}if err := cmd.Wait(); err != nil { log.Fatal(err)} fmt.Printf("%s is %d years old\n", person.Name, person.Age)}
func (c *Cmd) Wait() error
等待等待命令退出并等待任何復(fù)制到標(biāo)準(zhǔn)輸入或從標(biāo)準(zhǔn)輸出或標(biāo)準(zhǔn)錯(cuò)誤復(fù)制完成。
該命令必須由 Start 啟動。
如果命令運(yùn)行,則返回的錯(cuò)誤為零,在復(fù)制 stdin,stdout 和 stderr 時(shí)沒有問題,并以零退出狀態(tài)退出。
如果該命令無法運(yùn)行或未成功完成,則錯(cuò)誤類型為 * ExitError 。其他錯(cuò)誤類型可能會返回 I/O 問題。
如果 c.Stdin 不是 * os.File,則 Wait 還會等待從 c.Stdin 復(fù)制到流程的標(biāo)準(zhǔn)輸入的 I/O 循環(huán)完成。
等待釋放與 Cmd 相關(guān)的任何資源。
錯(cuò)誤記錄了未能執(zhí)行的二進(jìn)制文件的名稱及其失敗的原因。
type Error struct { Name string Err error}
func (e *Error) Error() string
ExitError 通過命令報(bào)告不成功的退出。
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}
func (e *ExitError) Error() string