douzhuo3233
2014-09-02 22:01 阅读 208
已采纳

如何在Golang中为exec.command添加空格

How do I use exec.command to start a file with spaces? Adding quotes doesn't seem to work, neither does " or %20 instead of the spaces.

package main

import (
"fmt"
"os/exec"
)

func main() {
    StartProcess("C:\\File With Spaces.txt")
}

func StartProcess(Filename string) {
    Filename = "\"" + Filename + "\""
    cmd := exec.Command("cmd","/C start",Filename)
    err := cmd.Start()
    if err!=nil{
    fmt.Println(err)
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dougu1045 dougu1045 2014-09-03 12:23

    This works, but only in windows

    cmd := exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", Filename)
    
    点赞 评论 复制链接分享
  • duanci1939 duanci1939 2014-09-02 22:11

    you need to cmd.Wait and check for any errors returned by your methods

    package main
    
    import (
        "bytes"
        "log"
        "os"
        "os/exec"
    )
    
    func main() {
        args := os.Args
    
        cmd := exec.Command(args[1], args[2:]...)
        var b bytes.Buffer
        cmd.Stdout = &b
    
        err := cmd.Start()
        if err != nil {
            log.Fatal(err)
        }
        if err := cmd.Wait(); err != nil {
            log.Fatal(err)
        }
    
        if _, err := os.Stdout.Write(b.Bytes()); err != nil {
            log.Fatal(err)
        }
    }
    
    点赞 评论 复制链接分享
  • doouzlrvb01417498 doouzlrvb01417498 2014-09-02 22:28

    If you're trying to run an executable on Windows then you don't need command prompt. You just need to pass in the executable path to the shell and it will fire.

    E.g:

    func StartProcess(Filename string) {
        // Filename = "cmd /C start \"" + Filename + "\"" 
        cmd := exec.Command(Filename)
        err := cmd.Start()
        if err!=nil{
        fmt.Println(err)
        }
    }
    
    StartProcess("C:\\path to executable\\executable.exe")
    

    That said, generally with all frameworks on Windows that start executables (Go appears to be included in this) you get in trouble when trying to concatenate your own arguments. That is why the args argument for exec.Command is variadic. So your original should have been this:

    cmd := exec.Command("cmd", "/C", "start", Filename)
    //                         ^^^^^^^^^^^^^^^ variadic arguments make Windows happy
    
    点赞 评论 复制链接分享

相关推荐