how I can return value with a same type using exec.Command().Output()

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

how I can return value with a same type using exec.Command().Output()

问题

在下一个示例中,我正在使用nodejs来计算1+1,并且我希望结果具有相同类型的值,而不是字符串。

示例代码:

func main() {
    cmd := exec.Command("/usr/bin/nodejs", "-p", "1+1")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        log.Println(err, stderr.String())
        os.Exit(1)
    }

    fmt.Println(out.String())
}

有没有办法做到这一点?

英文:

in the next example, I am using nodejs to calculate 1+1 and I want the result with a same type of value, not string

example:

func main() {
	cmd := exec.Command("/usr/bin/nodejs", "-p", "1+1")
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		log.Println(err, stderr.String())
		os.Exit(1)
	}

	fmt.Println(out.String())
}

is there way to do that?

答案1

得分: 2

执行命令时,你会得到一个字符串作为返回值。你需要对其进行反序列化以获取正确的类型。如果你只期望你的 Node.js 命令打印数字,你可以使用 strconv.ParseFloat

func main() {
    cmd := exec.Command("/usr/bin/nodejs", "-p", "1+1")
    b, err := cmd.Output()
    v, err := strconv.ParseFloat(string(b), 64)
    fmt.Println(v) // v 是 float64 类型
}

如果你想处理更复杂的类型,比如 JavaScript 对象和数组,我建议使用 JSON 进行序列化/反序列化 node 的结果:

type Result struct {
    Value float64
    Args []float64
}
func main() {
    var result Result
    cmd := exec.Command("/usr/bin/nodejs", "-p", `JSON.stringify({"value": 1+1, "args": [1, 1]})`)
    b, err := cmd.Output()
    err = json.Unmarshal(b, &result)
    fmt.Println(result.Value)
}
英文:

When executing a command, you get a string back. You will need to deserialize it to get the proper type back. If you only expect your Node.js command to print numbers, you can use strconv.ParseFloat:

func main() {
    cmd := exec.Command("/usr/bin/nodejs", "-p", "1+1")
    b, err := cmd.Output()
    v, err := strconv.ParseFloat(string(b), 64)
    fmt.Println(v) // v is of type float64
}

If you want to handle more complex types such as javascript objects and array, I suggest serializing/deserializing node's result using JSON:

type Result struct {
    Value float64
    Args []float64
}
func main() {
    var result Result
    cmd := exec.Command("/usr/bin/nodejs", "-p", `JSON.stringify({"value": 1+1, "args": [1, 1]})`)
    b, err := cmd.Output()
    err = json.Unmarshal(b, &r)
    fmt.Println(r.Value)
}

huangapple
  • 本文由 发表于 2017年7月15日 00:44:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45107967.html
匿名

发表评论

匿名网友

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

确定