亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

?? ??? ??
archive archive/tar archive/zip bufio bufio(緩存) builtin builtin(內(nèi)置包) bytes bytes(包字節(jié)) compress compress/bzip2(壓縮/bzip2) compress/flate(壓縮/flate) compress/gzip(壓縮/gzip) compress/lzw(壓縮/lzw) compress/zlib(壓縮/zlib) container container/heap(容器數(shù)據(jù)結(jié)構(gòu)heap) container/list(容器數(shù)據(jù)結(jié)構(gòu)list) container/ring(容器數(shù)據(jù)結(jié)構(gòu)ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(數(shù)據(jù)庫/sql) database/sql/driver(數(shù)據(jù)庫/sql/driver) debug debug/dwarf(調(diào)試/dwarf) debug/elf(調(diào)試/elf) debug/gosym(調(diào)試/gosym) debug/macho(調(diào)試/macho) debug/pe(調(diào)試/pe) debug/plan9obj(調(diào)試/plan9obj) encoding encoding(編碼) encoding/ascii85(編碼/ascii85) encoding/asn1(編碼/asn1) encoding/base32(編碼/base32) encoding/base64(編碼/base64) encoding/binary(編碼/binary) encoding/csv(編碼/csv) encoding/gob(編碼/gob) encoding/hex(編碼/hex) encoding/json(編碼/json) encoding/pem(編碼/pem) encoding/xml(編碼/xml) errors errors(錯(cuò)誤) expvar expvar flag flag(命令行參數(shù)解析flag包) fmt fmt go go/ast(抽象語法樹) go/build go/constant(常量) go/doc(文檔) go/format(格式) go/importer go/parser go/printer go/scanner(掃描儀) go/token(令牌) go/types(類型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(圖像) image/color(顏色) image/color/palette(調(diào)色板) image/draw(繪圖) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系統(tǒng)) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路徑) plugin plugin(插件) reflect reflect(反射) regexp regexp(正則表達(dá)式) regexp/syntax runtime runtime(運(yùn)行時(shí)) runtime/debug(調(diào)試) runtime/internal/sys runtime/pprof runtime/race(競爭) runtime/trace(執(zhí)行追蹤器) sort sort(排序算法) strconv strconv(轉(zhuǎn)換) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系統(tǒng)調(diào)用) testing testing(測試) testing/iotest testing/quick text text/scanner(掃描文本) text/tabwriter text/template(定義模板) text/template/parse time time(時(shí)間戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
??

  • 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)行。

Index

  • 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

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)}

type Cmd

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

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())}

示例(環(huán)境)

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

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 (*Cmd) CombinedOutput

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 (*Cmd) Output

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 (*Cmd) Run

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 (*Cmd) Start

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 (*Cmd) StderrPipe

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 (*Cmd) StdinPipe

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 (*Cmd) StdoutPipe

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 (*Cmd) Wait

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)的任何資源。

type Error

錯(cuò)誤記錄了未能執(zhí)行的二進(jìn)制文件的名稱及其失敗的原因。

type Error struct {
        Name string
        Err  error}

func (*Error) Error

func (e *Error) Error() string

type ExitError

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 (*ExitError) Error

func (e *ExitError) Error() string
?? ??: ?? ??: