How to execute a simple Windows command in Golang?

后端 未结 6 1976
执念已碎
执念已碎 2020-12-08 10:06

How to run a simple Windows command?

This command:

exec.Command(\"del\", \"c:\\\\aaa.txt\")

.. outputs th

6条回答
  •  没有蜡笔的小新
    2020-12-08 11:03

    you can try use github.com/go-cmd/cmd module.
    because golang can not use syscall by default.

    example:

    import (
        "fmt"
        "time"
        "github.com/go-cmd/cmd"
    )
    
    func main() {
        // Start a long-running process, capture stdout and stderr
        findCmd := cmd.NewCmd("find", "/", "--name", "needle")
        statusChan := findCmd.Start() // non-blocking
    
        ticker := time.NewTicker(2 * time.Second)
    
        // Print last line of stdout every 2s
        go func() {
            for range ticker.C {
                status := findCmd.Status()
                n := len(status.Stdout)
                fmt.Println(status.Stdout[n-1])
            }
        }()
    
        // Stop command after 1 hour
        go func() {
            <-time.After(1 * time.Hour)
            findCmd.Stop()
        }()
    
        // Check if command is done
        select {
        case finalStatus := <-statusChan:
            // done
        default:
            // no, still running
        }
    
        // Block waiting for command to exit, be stopped, or be killed
        finalStatus := <-statusChan
    }
    

提交回复
热议问题