Getting Python version using Go

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

Getting Python version using Go

问题

我正在尝试使用Go获取我的Python版本:

  1. import (
  2. "log"
  3. "os/exec"
  4. "strings"
  5. )
  6. func verifyPythonVersion() {
  7. _, err := exec.LookPath("python")
  8. if err != nil {
  9. log.Fatalf("未找到Python版本")
  10. }
  11. out, err := exec.Command("python", "--version").Output()
  12. log.Print(out)
  13. if err != nil {
  14. log.Fatalf("使用'python'命令检查Python版本时出错:%v", err)
  15. }
  16. fields := strings.Fields(string(out))
  17. log.Print(fields)
  18. }
  19. func main() {
  20. verifyPythonVersion()
  21. }

这将返回空切片:

  1. 2014/01/03 20:39:53 []
  2. 2014/01/03 20:39:53 []

有任何想法我做错了什么吗?

英文:

I'm trying to get my Python version using Go:

  1. import (
  2. "log"
  3. "os/exec"
  4. "strings"
  5. )
  6. func verifyPythonVersion() {
  7. _, err := exec.LookPath("python")
  8. if err != nil {
  9. log.Fatalf("No python version located")
  10. }
  11. out, err := exec.Command("python", "--version").Output()
  12. log.Print(out)
  13. if err != nil {
  14. log.Fatalf("Error checking Python version with the 'python' command: %v", err)
  15. }
  16. fields := strings.Fields(string(out))
  17. log.Print(fields)
  18. }
  19. func main() {
  20. verifyPythonVersion()
  21. }

This returns empty slices:

  1. 2014/01/03 20:39:53 []
  2. 2014/01/03 20:39:53 []

Any idea what I'm doing wrong?

答案1

得分: 8

以下是翻译好的内容:

  1. $ python --version
  2. Python 2.7.2
  3. $ python --version 1>/dev/null # 隐藏标准输出
  4. Python 2.7.2
  5. $ python --version 2>/dev/null # 隐藏标准错误输出
  6. 我们可以得出结论,输出结果是发送到标准错误输出(stderr)。现在我查看了Go的文档,猜猜看,`cmd.Output`只捕获标准输出([文档](http://golang.org/pkg/os/exec/#Cmd.Output))。你应该使用`cmd.CombinedOutput`([文档](http://golang.org/pkg/os/exec/#Cmd.CombinedOutput)):
  7. > CombinedOutput运行命令并返回其合并的标准输出和标准错误输出。
英文:
  1. $ python --version
  2. Python 2.7.2
  3. $ python --version 1>/dev/null # hide stdout
  4. Python 2.7.2
  5. $ python --version 2>/dev/null # hide stderr

We can conclude that the output goes to stderr. Now I took a look at Go's docs, and guess what, cmd.Output only captures stdout (docs). You should use cmd.CombinedOutput (docs) :

> CombinedOutput runs the command and returns its combined standard output and standard error.

huangapple
  • 本文由 发表于 2014年1月4日 01:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/20909598.html
匿名

发表评论

匿名网友

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

确定