Home >Backend Development >Golang >How to execute cmd command line in Golang

How to execute cmd command line in Golang

藏色散人
藏色散人forward
2020-12-04 14:48:198369browse

The following column golang tutorial will introduce to you the method of Golang. I hope it will help you if you need it. Friends help!

How to execute cmd command line in Golang

1. Golang executes system commands using the os/exec Command method:

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

The first parameter is the command name, and the following parameters can have multiple commands. parameter.

cmd := exec.Command("ls", "-a")
if stdout, err := cmd.StdoutPipe(); err != nil {     //获取输出对象,可以从该对象中读取输出结果
    log.Fatal(err)
}
defer stdout.Close()   // 保证关闭输出流
 
if err := cmd.Start(); err != nil {   // 运行命令
    log.Fatal(err)
}
 
if opBytes, err := ioutil.ReadAll(stdout); err != nil {  // 读取输出结果    
    log.Fatal(err)
} else {
    log.Println(string(opBytes))
}

2. Redirect the output of the command to a file:

 stdout, err := os.OpenFile("stdout.log", os.O_CREATE|os.O_WRONLY, 0600)   
    if err != nil {
        log.Fatalln(err)
    }
    defer stdout.Close()
    cmd.Stdout = stdout   // 重定向标准输出到文件
    // 执行命令
    if err := cmd.Start(); err != nil {
        log.Println(err)
    }

3. The difference between the Start and Run methods of cmd:

Start execution will not wait for the command to complete, and Run will block waiting for the command to complete.

cmd := exec.Command("sleep", "10")
err := cmd.Run()  //执行到此处时会阻塞等待10秒
err := cmd.Start()   //如果用start则直接向后运行
if err != nil {
    log.Fatal(err)
}
err = cmd.Wait()   //执行Start会在此处等待10秒

4. If the command name and parameters are written as a string and passed to the Command method, the execution may fail with an error: file does not exist, but at this time, if you force start a Execution in a DOS window (windows platform) is also successful.

On the Windows platform, force the DOS window to pop up to execute the command line:

cmdLine := pscp -pw pwd local_filename user@host:/home/workspace   
cmd := exec.Command("cmd.exe", "/c", "start " + cmdLine)
err := cmd.Run()
fmt.Printf("%s, error:%v \n", cmdLine, err)

5. Hide the golang program's own cmd window when running:

 go build -ldflags -H=windowsgui

6. Windows On the platform, execute the system command to hide the cmd window:

cmd := exec.Command("sth")
 if runtime.GOOS == "windows" {
     cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
 }
 err := cmd.Run()

The above is the detailed content of How to execute cmd command line in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete