英文:
Exit stauts 1 in golang
问题
这是一个简单的函数,它在没有任何进一步提示的情况下抛出退出状态为1的错误。
func execute_this(cmd string) string {
out, err := exec.Command("cmd", "/C", cmd).Output()
if err != nil {
log.Fatal(err)
fmt.Println(out)
}
fmt.Println(string(out))
return string(out)
}
func main() {
var cmd string
var result string
cmd = "pwd"
result = execute_this(cmd)
fmt.Println(result)
}
抛出的错误信息为:
2021/10/27 01:12:06 exit status 1
exit status 1
目标是编写一个函数,在shell中执行系统命令,并将输出作为字符串返回。
英文:
Got this simple function that throws and error with exit status 1 without any further hints to why this is happening
func execute_this(cmd string ) string {
out, err := exec.Command("cmd","/C", cmd).Output()
if err != nil {
log.Fatal(err)
fmt.Println(out)
}
fmt.Println(string(out))
return string(out)
}
func main() {
var cmd string
var result string
cmd = "pwd"
result = execute_this(cmd)
fmt.Println(result)
}
throw error message
2021/10/27 01:12:06 exit status 1
exit status 1
The goal is to write a function that executes system commands in shell and returning the output as a string
答案1
得分: 2
尝试这个方法,它将允许你同时看到发送到 stderr 的输出。详细信息请参考这里。
具体来说,在你的情况下,问题是:
'pwd' 不被识别为内部或外部命令、可操作的程序或批处理文件。
package main
import (
"fmt"
"log"
"os/exec"
"os"
)
func execute_this(cmd string ) string {
c := exec.Command("cmd","/C", cmd)
c.Stderr = os.Stderr
out, err := c.Output()
if err != nil {
log.Fatal(err)
}
return string(out)
}
func main() {
cmd := "pwd"
result := execute_this(cmd)
fmt.Println(result)
}
英文:
Try this, it will allow you to also see the output sent to the stderr. Details here.
Specifically, in your case, the problem is that
'pwd' is not recognized as an internal or external command,
operable program or batch file.
package main
import (
"fmt"
"log"
"os/exec"
"os"
)
func execute_this(cmd string ) string {
c := exec.Command("cmd","/C", cmd)
c.Stderr = os.Stderr
out, err := c.Output()
if err != nil {
log.Fatal(err)
}
return string(out)
}
func main() {
cmd := "pwd"
result := execute_this(cmd)
fmt.Println(result)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论