在golang中的退出状态为1。

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

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

huangapple
  • 本文由 发表于 2021年10月27日 06:17:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/69730591.html
匿名

发表评论

匿名网友

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

确定