可执行文件不在路径中 – GO

huangapple go评论96阅读模式
英文:

Executable files not in path - GO

问题

我正在尝试调用命令提示符的内置命令,但是我遇到了我不理解的错误。

func main() {
    cmd := exec.Command("del", "C:\trial\now.txt")
    // 如果需要重新启动
    cmd.Stdout = os.Stdout
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}

我得到了以下错误:

exec: "del": 在 %PATH% 中找不到可执行文件
exit status 1

我做错了什么?

英文:

I'm trying to call a built in command for the command prompt and I'm getting errors I don't understand.

func main() {
    cmd := exec.Command("del", "C:\trial\now.txt")
// Reboot if needed
    cmd.Stdout = os.Stdout
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}

And I'm getting the following error:

exec: "del": executable file not found in %PATH%
exit status 1

What am I doing wrong?

答案1

得分: 8

del 不是一个可执行文件,它是一个内置命令。exec.Command 允许你调用另一个可执行文件。要使用 shell 命令,你需要调用 shell 可执行文件,并传入你想要执行的内置命令(和参数):

cmd := exec.Command("cmd.exe", "/C", "del C:\\trial\\now.txt")

请注意,你还需要在字符串中转义反斜杠,如上所示,或者使用反引号括起来的字符串:

cmd := exec.Command("cmd.exe", "/C", `del C:\trial\now.txt`)

然而,如果你只是想删除一个文件,你可能最好直接使用 os.Remove 函数来删除文件,而不是调用 shell 来执行。

英文:

del is not an executable, it's a built-in command. exec.Command allows you to fork out to another executable. To use shell commands, you would have to call the shell executable, and pass in the built-in command (and parameters) you want executed:

cmd := exec.Command("cmd.exe", "/C", "del C:\\trial\\now.txt")

Note that you also have to escape backslashes in strings as above, or use backtick-quoted strings:

cmd := exec.Command("cmd.exe", "/C", `del C:\trial\now.txt`)

However, if you just want to delete a file, you're probably better off using os.Remove to directly delete a file rather than forking out to the shell to do so.

答案2

得分: 2

除了可执行文件的问题之外,你的路径字符串并不是你想象中的那样。

cmd := exec.Command("del", "C:\trial\now.txt")

\t将被解释为制表符,\n将被解释为换行符。

为了避免这种情况,使用``,它没有特殊字符,也没有转义,甚至没有\。这对于Windows用户来说是一个很大的解脱!

cmd := exec.Command("del", `C:\trial\now.txt`)

请参阅Go语言规范中的字符串字面值了解更多信息。

英文:

In addition to the problem with the executable, your path string is not what you think it is.

cmd := exec.Command("del", "C:\trial\now.txt")

The \t will be interpreted as a tab, and the \n as a newline.

To avoid this, use `` which has no special characters and no escape, not even \. A great relief for Windows users!

cmd := exec.Command("del", `C:\trial\now.txt`)

See String Literals in the Go Language Spec for more.

huangapple
  • 本文由 发表于 2017年6月30日 03:02:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44833044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定