How to get output from os.exec in go

PHPz
Release: 2024-02-08 21:30:29
forward
1056 people have browsed it

如何从 go 中的 os.exec 获取输出

在使用Go语言中的os.exec包时,获取命令执行的输出是一个常见的需求。但是,由于os.exec包的设计特点,直接获取输出并不是一件简单的事情。那么,如何从Go语言中的os.exec中获取命令的输出呢?在本文中,我们将为大家详细介绍一种简单有效的方法,帮助大家解决这个问题。无论你是初学者还是有经验的开发者,相信本文都能对你有所帮助。让我们一起来看看吧!

问题内容

我正在尝试从以下代码获取系统输出

cmdstring := "lxc exec " + containername + " -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1"
ip, err := exec.command("bash", "-c", cmdstring).output()
fmt.println(ip)
Copy after login

上面的代码应该从 lxc 容器获取 ip 地址。

go的实际输出是[]

我也尝试过以下方法

ip, err := exec.command("lxc", "exec ", containername, " --", "ip addr show eth0", "|", "grep", "'inet\b'", "| awk '{print $2}'", "| cut -d/", "-f1").output()
fmt.println(ip)
Copy after login

我仍然只得到 [] 作为输出

命令行的正确输出如下

[root@localhost toolbox]# lxc exec simon -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1
10.183.201.38
Copy after login

知道我做错了什么吗?

解决方法

阅读这段代码,您就可以了解如何读取结果的标准输出

package main

import (
    "bytes"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("/usr/bin/ls")
    buf := bytes.Buffer{}
    cmd.Stdout = &buf
    err := cmd.Run()

    fmt.Println(buf.String(), err)
}
Copy after login

The above is the detailed content of How to get output from os.exec in go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!