exec.Command(“date”) 无法找到 date 命令。

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

exec.Command("date") not able to find date command

问题

以下是代码的中文翻译:

package main

import (
	"fmt"
	"log"
	"os/exec"
)

func main() {
	out, err := exec.Command("date").Output()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("The date is %s\n", out)
}

这是一个执行系统命令的文档示例代码。http://golang.org/pkg/os/exec/#example_Cmd_Output 即使在文档网站上,示例执行框也无法运行,并显示相同的错误:
2009/11/10 23:00:00 exec: "date": 在 $PATH 中找不到可执行文件

在 Windows 上,我得到的错误是:
exec: "date": 在 %PATH% 中找不到可执行文件

如何使命令正常工作?我需要设置路径或写出命令的完整路径吗?

英文:
package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
    	log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}

This is a code example from the documentation for executing system commands. http://golang.org/pkg/os/exec/#example_Cmd_Output Even on the documentation site the example execute box doesn't run and has the same error:
2009/11/10 23:00:00 exec: "date": executable file not found in $PATH

On Windows I get:
exec: "date": executable file not found in %PATH%

How do I get commands to work? Do I need to set a path or write out the full path of the command?

答案1

得分: 4

很遗憾,除非你从某个地方(比如Cygwin)获取一个date.exe并将其放在%PATH%中,否则这个示例对你来说是行不通的。

我认为问题出在于date在Powershell中是一个内置命令。它对你起作用是因为你的shell正在解释它。

你可以尝试执行以下命令:

out, err := exec.Command("cmd", "/C", "date").Output()

参考这里的建议;不过我不确定,因为我手边没有Windows机器。


附注:

> Get-Command date显示“未将名称为'date'的 cmdlet 识别为 cmdlet 的名称”

这个短语在谷歌上只有两个结果。其中一个结果引导我到了这里,帮助我解决了这个问题。

英文:

Sadly, that example isn't going to work for you unless you get a date.exe from somewhere (Cygwin?) and put in on your %PATH%.

What's going on, I believe, is that date is a builtin in Powershell. It works for you because your shell is interpreting it.

You may be able to do

out, err := exec.Command("cmd", "/C", "date").Output()

as suggested here; I don't know, I don't have a Windows machine handy.


Sidenote:

> Get-Command date says "The term 'date' is not recognized as the name of a cmdlet"

There are exactly two Google results for that phrase. One of them leads me to this, which helped me figure this out.

答案2

得分: 2

在Windows上,由于date不是一个可执行文件,我将你的代码修改为以下方式运行:

out, err := exec.Command("cmd.exe", "/c date /t").Output()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)

输出结果为:

The date is Fri 25/10/2013
英文:

On windows since date is not a executable, I changed your code to run as follows:

out, err := exec.Command("cmd.exe", " /c date /t").Output()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)

The output:

The date is Fri 25/10/2013

huangapple
  • 本文由 发表于 2013年10月25日 08:44:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/19579238.html
匿名

发表评论

匿名网友

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

确定