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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。