登录
首页 >  Golang >  Go问答

使用Golang执行cmd命令时禁止输出标准输出

来源:stackoverflow

时间:2024-02-19 15:12:41 246浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用Golang执行cmd命令时禁止输出标准输出》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

cmdstr := "ssh -i ....... blah blah blah" ssh to an ip and run rpm command to install rpm
cmd := exec.Command("/bin/bash", "-c", cmdstr)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
    fmt.Println(out.String())
}

out.string() 不打印任何内容 如果我有 ping 命令但没有 /bin/bash 它会打印出来。有人知道为什么吗?


正确答案


cmd.stdout 捕获成功命令执行的输出
cmd.stderr 在执行过程中发生错误时捕获命令输出

您可以尝试使用 cmd.output() 变体并使用 stderr 捕获执行错误

cmdstr := "ssh -i ....... blah blah blah" // ssh to an ip and run rpm command to install rpm
cmd := exec.Command("/bin/bash", "-c", cmdstr)
var errb bytes.Buffer
cmd.Stderr = &errb
output, err := cmd.Output()
if err != nil {
    fmt.Printf("error: %s", errb.String()) // capture any error output
}

fmt.Println(string(output)) // when successful

本篇关于《使用Golang执行cmd命令时禁止输出标准输出》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>