Example 1:
package main import ( "bufio" "fmt" "os" "os/exec" //"strings" ) func main() { reader := bufio.NewReader(os.Stdin) cmdString, err := reader.ReadString('\n') if err != nil { fmt.Fprintln(os.Stderr, err) } fmt.Println(cmdString) //cmdString = strings.TrimSuffix(cmdString, "\n") cmdString = cmdString[:len(cmdString)-2] cmd := exec.Command(cmdString) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout cmd.Run() }
windows built-in command examples
package main import ( "fmt" "os/exec" ) func main() { c := exec.Command("cmd", "/C", "del", "D:\\a.txt") exec.Command() if err := c.Run(); err != nil { fmt.Println("Error: ", err) } }
golang os / exec execute external commands
Package exec execute external commands, it os.StartProcess packaging makes it easier to stdin and stdout maps, and with pipe connections i / o.
func LookPath(file string) (string, error) //LookPath
LookPath find families in an environment variable to perform binary file, if the file contains a slash, then go directly to find the absolute or relative path relative to catalog
package main import ( "fmt" "os/exec" ) func main() { f, err := exec.LookPath("curl") if err != nil { fmt.Println(err) } fmt.Println(f) // /bin/ls }
Output:
D:\curl\curl.exe
type Cmd // represents one is ready or running an external command
Cmd {struct of the type Path String // path to run the command, absolute or relative path Args [] string // command parameter Env [] string // process environment, if the environment is empty, the current process environment Dir string // Specifies the command of the working directory, if dir is empty, then comman run in the current directory where the calling process stdin io.Reader // standard input, if stdin is nil, then the process of reading (os.DevNull) from the null device, stdin when a file is also possible, otherwise it during operation to open a goroutine go // read standard input stdout io.Writer // standard output Stderr io.Writer // error output if the two (stdout and Stderr) is empty, then the command to run the file descriptor of the response to the connection os.DevNull ExtraFiles [] * os.File SysProcAttr * syscall.SysProcAttr process os.Process * // process the underlying process is started only once ProcessState * os. ProcessState // ProcessState contains information of an exit process, when the process calls Wait or Run will produce the information. }
func Command (name string, arg ... string) * Cmd // command cmd returns to execute commands with configuration parameters, which set only cmd Path and Args structure parameters, if not included in the path name argument separator Fu, command using LookPath path to solve the problem, otherwise the direct use of name; Args directly after the command command, there is no need to add the command in Args.
package main import ( "bytes" "fmt" "log" "os/exec" "strings" ) func main() { cmd := exec.Command("cmd.exe", "C", "dir") 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()) }
func (c * Cmd) CombinedOutput () ([] byte, error) // run command, and return to the standard output and standard error
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) } fmt.Println(string(out)) }
func (c * Cmd) Output () ([] byte, error) // run command and returns its standard output
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") out, err := cmd.Output() if err != nil { fmt.Println(err) } fmt.Println(string(out)) }
Note: Output () and CombinedOutput () can not be used simultaneously, because the standard output of the command can be only one, then it will use the definition of the two, will be given
func (c * Cmd) Run ( ) error // start the specified command and wait for him to finish, and if the command can be executed successfully completed, it returns nil, otherwise side generates an error func (c * Cmd) Start ( ) error // a command to start the execution, but not until the end of his execution, and Run this command are different. Then finished using a method Wait and wait for the command to release the response resources
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") err := cmd.Run() if err != nil { fmt.Println(err) } fmt.Println(cmd.Start()) }
Output:
exec: already started
Note: Use only a command Start () or Run () in a start command, not both simultaneously.
func (c * Cmd) StderrPipe ( ) (io.ReadCloser, error) // StderrPipe a return pipe, the pipe is connected to the standard error command, when the command command exits, the Wait shuts down pipe FUNC (C * Cmd) StdinPipe () (io.WriteCloser, error) // StdinPipe return conduit connected to a standard input pipe command
package main import ( "fmt" "os" "os/exec" ) func main() { cmd := exec.Command("cat") stdin, err := cmd.StdinPipe() if err != nil { fmt.Println(err) } _, err = stdin.Write([]byte("tmp.txt")) if err != nil { fmt.Println(err) } stdin.Close() cmd.Stdout = os.Stdout cmd.Start() }
func (c * Cmd) StdoutPipe () (io.ReadCloser, error) // StdoutPipe return pipe connected to the pipe a standard command output
package main import ( "fmt" "io/ioutil" "os/exec" "time" ) func main() { cmd := exec.Command("dir") stdout, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) } cmd.Run() go func() { content, err := ioutil.ReadAll(stdout) if err != nil { fmt.Println("err: ", err) } fmt.Println(string(content)) }() time.Sleep(1 * time.Second) fmt.Println("main is ending") }
func (c * Cmd) Wait () error // Wait wait for the command to exit, he must be used with Start, if able to successfully executing the command exit successfully returns nil, otherwise it will return error, which would be let go Wait All resources associated with the cmd command
type Error // Error returns an error Section execute binary file name of reason can not be executed
type Error struct { Name string Err error
FUNC (E * Error) Error () String of the type ExitError // a command can not be normal exit error
type ExitError struct { *os.ProcessState }
func (e *ExitError) Error() string
Package exec execute external commands, it os.StartProcess packaging makes it easier to stdin and stdout maps, and with pipe connections i / o.
func LookPath(file string) (string, error) //LookPath
LookPath find families in an environment variable to perform binary file, if the file contains a slash, then go directly to find the absolute or relative path relative to catalog
package main import ( "fmt" "os/exec" ) func main() { f, err := exec.LookPath("curl") if err != nil { fmt.Println(err) } fmt.Println(f) // /bin/ls }
Output:
D:\curl\curl.exe
type Cmd // represents one is ready or running an external command
Cmd {struct of the type Path String // path to run the command, absolute or relative path Args [] string // command parameter Env [] string // process environment, if the environment is empty, the current process environment Dir string // Specifies the command of the working directory, if dir is empty, then comman run in the current directory where the calling process stdin io.Reader // standard input, if stdin is nil, then the process of reading (os.DevNull) from the null device, stdin when a file is also possible, otherwise it during operation to open a goroutine go // read standard input stdout io.Writer // standard output Stderr io.Writer // error output if the two (stdout and Stderr) is empty, then the file descriptor will respond to the command to run when connected to os.DevNull ExtraFiles [] * os.File SysProcAttr * syscall.SysProcAttr process * os.Process // process the underlying process is started only once ProcessState * os. ProcessState // ProcessState contains information of an exit process, when the process calls Wait or Run will produce the information. }
func Command (name string, arg ... string) * Cmd // command cmd returns to execute commands with configuration parameters, which set only cmd Path and Args structure parameters, if not included in the path name argument separator Fu, command using LookPath path to solve the problem, otherwise the direct use of name; Args directly after the command command, there is no need to add the command in Args.
package main import ( "bytes" "fmt" "log" "os/exec" "strings" ) func main() { cmd := exec.Command("cmd.exe", "C", "dir") 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()) }
func (c * Cmd) CombinedOutput () ([] byte, error) // run command, and return to the standard output and standard error
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) } fmt.Println(string(out)) }
func (c * Cmd) Output () ([] byte, error) // run command and returns its standard output
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") out, err := cmd.Output() if err != nil { fmt.Println(err) } fmt.Println(string(out)) }
Note: Output () and CombinedOutput () can not be used simultaneously, because the standard output of the command can be only one, then it will use the definition of the two, will be given
func (c * Cmd) Run ( ) error // start the specified command and wait for him to finish, and if the command can be executed successfully completed, it returns nil, otherwise side generates an error func (c * Cmd) Start ( ) error // a command to start the execution, but not until the end of his execution, and Run this command are different. Then finished using a method Wait and wait for the command to release the response resources
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd", "/C", "dir") err := cmd.Run() if err != nil { fmt.Println(err) } fmt.Println(cmd.Start()) }
Output:
exec: already started
Note: Use only a command Start () or Run () in a start command, not both simultaneously.
func (c * Cmd) StderrPipe ( ) (io.ReadCloser, error) // StderrPipe a return pipe, the pipe is connected to the standard error command, when the command command exits, the Wait shuts down pipe FUNC (C * Cmd) StdinPipe () (io.WriteCloser, error) // StdinPipe return conduit connected to a standard input pipe command
package main import ( "fmt" "os" "os/exec" ) func main() { cmd := exec.Command("cat") stdin, err := cmd.StdinPipe() if err != nil { fmt.Println(err) } _, err = stdin.Write([]byte("tmp.txt")) if err != nil { fmt.Println(err) } stdin.Close() cmd.Stdout = os.Stdout cmd.Start() }
func (c * Cmd) StdoutPipe () (io.ReadCloser, error) // StdoutPipe return pipe connected to the pipe a standard command output
package main import ( "fmt" "io/ioutil" "os/exec" "time" ) func main() { cmd := exec.Command("dir") stdout, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) } cmd.Run() go func() { content, err := ioutil.ReadAll(stdout) if err != nil { fmt.Println("err: ", err) } fmt.Println(string(content)) }() time.Sleep(1 * time.Second) fmt.Println("main is ending") }
func (c * Cmd) Wait () error // Wait wait for the command to exit, he must be used with Start, if able to successfully executing the command exit successfully returns nil, otherwise it will return error, which would be let go Wait All resources associated with the cmd command
type Error // Error returns an error Section execute binary file name of reason can not be executed
type Error struct { Name string Err error
FUNC (E * Error) Error () String of the type ExitError // a command can not be normal exit error
type ExitError struct { *os.ProcessState }
func (e *ExitError) Error() string