从exec.Command输出解析整数 [英] Parsing integer from exec.Command output

查看:149
本文介绍了从exec.Command输出解析整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正试图从我的Go程序中运行一个命令,并从响应中解析一个整数。该命令返回如下输出:


<6>
fyb_src / ex1.fyb(1)胜!


strings.Split strings.TrimSpaces 工作正常。然而,在尝试将数字解析为整数时,我得到以下错误:

lockquote
panic:strconv.ParseInt解析0 \ r1 \r2 \r3 \r4 \r5 \r6:语法无效

但是打印字符串试图解析到终端产生以下结果:
$ b


6


我不确定从哪里出发。这个数字对我来说显然看起来像一个整数。错误信息也没有用(至少对我而言)。有没有人有想法?



编辑:我正在运行的代码

  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())
}


解决方案

看来您的问题在于 parts [0] 包含字符串0 \r1 \r2 \r3 \r4 \r5 \r6而不是数字。



strconv.Atoi函数只查找一个数字进行解析 - 我假设您正试图在这种情况下获得第一个0。如果是这样,问题是这个代码: strings.Split(string(out),\\\
只会查找\ n而不是\\ \\ r,这显然是从 osx_fukyobrane_amd64

返回的内容。

解决方法是将如下所示:

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

这会将多条线合并为一条并处理\ r,\ n和\ r \ n(或其他奇怪的组合)作为有效的换行符。


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 \r1 \r2 \r3 \r4 \r5 \r6": 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), "\n")

    fmt.Println(parts[0])

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

解决方案

It would appear that your problem is that parts[0] contains the string "0 \r1 \r2 \r3 \r4 \r5 \r6" 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), "\n") is only looking for "\n" not "\r", which is apparently what is being returned from osx_fukyobrane_amd64.

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

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

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

这篇关于从exec.Command输出解析整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆