GO語言"os/exec"包中"Command"函數的用法及代碼示例。
用法:
func Command(name string, arg ...string) *Cmd
命令返回 Cmd 結構以執行具有給定參數的命名程序。
它僅在返回的結構中設置 Path 和 Args。
如果 name 不包含路徑分隔符,Command 會盡可能使用 LookPath 將 name 解析為完整路徑。否則它直接使用名稱作為路徑。
返回的 Cmd 的 Args 字段由命令名稱後跟 arg 的元素構成,因此 arg 不應包含命令名稱本身。例如,命令("echo"、"hello")。 Args[0] 始終是名稱,而不是可能解析的路徑。
在 Windows 上,進程將整個命令行作為單個字符串接收並進行自己的解析。 Command 使用與使用CommandLineToArgvW 的應用程序兼容的算法(這是最常見的方式)將 Args 組合表示到命令行字符串中。值得注意的例外是 msiexec.exe 和 cmd.exe(以及所有批處理文件),它們具有不同的取消引用算法。在這些或其他類似情況下,您可以自己進行引用並在SysProcAttr CmdLine 中提供完整的命令行,將 Args 留空。
例子:
package main
import (
"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 main
import (
"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)
}
}
相關用法
- GO CommandContext用法及代碼示例
- GO CommentMap用法及代碼示例
- GO Compare用法及代碼示例
- GO CopyN用法及代碼示例
- GO CopyBuffer用法及代碼示例
- GO ContainsRune用法及代碼示例
- GO Copysign用法及代碼示例
- GO Cosh用法及代碼示例
- GO Config用法及代碼示例
- GO Count用法及代碼示例
- GO ContainsAny用法及代碼示例
- GO Cos用法及代碼示例
- GO Conn.ExecContext用法及代碼示例
- GO Copy用法及代碼示例
- GO Contains用法及代碼示例
- GO Chmod用法及代碼示例
- GO Cmd.Start用法及代碼示例
- GO CanBackquote用法及代碼示例
- GO CreateTemp用法及代碼示例
- GO Cut用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Command。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。