如何在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)
    }
}

This works, but only in windows

cmd := exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", Filename)

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)
    }
}

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