duanmei1885 2016-06-10 21:57
浏览 91
已采纳

从exec.Command输出中解析整数

I'm currently trying to run a command from inside my Go program and parse an integer from the response. The command returns output like this:

6
fyb_src/ex1.fyb (1) wins!

Splitting the lines and removing the whitespace with strings.Split and strings.TrimSpaces works fine. However, while trying to parse the number into an integer I get the following error:

panic: strconv.ParseInt: parsing "0 1 2 3 4 5 6": invalid syntax

But printing the string I'm trying to parse to the terminal yields the following result:

6

I'm not really sure where to go from here. The number clearly looks like an integer to me. The error message isn't useful either (at least for me). Does anyone have an idea?

EDIT: The code I'm running

    out, _ := exec.Command(pwd+"/osx_fukyobrane_amd64", "fyb_src/"+filename, "fyb_src/salty.fyb", "t").CombinedOutput()
    parts := strings.Split(string(out), "
")

    fmt.Println(parts[0])

    rounds, err := strconv.Atoi(strings.TrimSpace(parts[0]))
    if err != nil {
        panic(err.Error())
    }
  • 写回答

3条回答 默认 最新

  • dqdpz60048 2016-06-10 22:23
    关注

    It would appear that your problem is that parts[0] contains the string "0 1 2 3 4 5 6" instead of a number.

    The strconv.Atoi function is looking for just one number to parse - I assume you are trying to get that first "0" in this case. If so, the problem is that this code: strings.Split(string(out), " ") is only looking for " " not "", which is apparently what is being returned from osx_fukyobrane_amd64.

    One solution would be to instead split the lines like this:

    regexp.MustCompile(`[
    ]+`).Split(parts[0], -1)
    

    That will collapse multiple lines together into one and treat , , and (or other weird combinations) as valid line breaks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?