duanshan188866 2018-10-10 12:06
浏览 179

如何使用golang运行dir命令?

Here is my code:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func runCommand(command string) io.Writer{
    cmdName := "cmd.exe"
    cmdArgs := []string{"/c", command}
    fmt.Println("Running command: " + command)
    cmd := exec.Command(cmdName, cmdArgs...)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    cmd.Run()
    return cmd.Stdout

}
func main(){
    fmt.Println(runCommand("dir"))  // Prints the output of dir for the current directory
    fmt.Println(runCommand("dir C:\\")) // Prints nothing
    fmt.Println(runCommand("dir C:\\Users\\"))  //Prints the output of dir for the users directory
    fmt.Println(runCommand("dir C:\\..\\"))  // Prints the output of dir for the C drive (What I want)
}

I'm expecting that when I execute dir C:\ That I would get the output as if I had ran in in a windows command prompt. Instead I get nothing. Intestingly, any other path when running dir works just fine. I can even see C:\ If I instead execute C:\..\ Why is this? I don't understand why this happens, and every other windows command I have given it works fine.

  • 写回答

1条回答 默认 最新

  • duanchendu69495 2018-10-10 12:29
    关注

    First of all, never ignore errors. The call to cmd.Run() returns an error, you should always check it:

    if err := cmd.Run(); err != nil {
        fmt.Printf(os.Stderr, "%v", err)
    }
    

    Try that and you might see why your command is failing.

    Without knowing the error, it's hard to help fixing your problem, but I'd guess you need to split the string command into several fields and append them to cmdArgs. When running runCommand("dir C:\\"), your cmdArgs is actually []string{"/c", "dir C:\\"), I think it should be []string{"/c", "dir", "C:\\"}. Take a look at the function strings.Split(string, string), it might help you. But that's just a guess, we need to know the exact error message you're having for a proper solution :)

    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题