Capturing python code error using Go lang

Hi All,

Trying to execute python file using go lang .I am able to get the output when the python code is working but unable to capture python error when python code has some errors

i am using this command :
out,err1:= exec.Command( “python”,“samples1.py”).Output();

out captures python code output if python file gets executed
err1 captures go lang errors.

How to capture python code errors ??

plzz help me asap @NobbZ @lutzhorn

You probably want to read from stderr, or see CombinedOutput.

The simplest way is in fact as @calmh already suggests to take a look at Cmd.CombinedOutput(). It will interleave stderr and stdout though, which is not always what you want.

Another way is to create 2 io.Writers and assign them to Cmd.Stdout and Cmd.Stderr. I’ve often used it roughly like this:

var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command("echo", "bar")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
cmd.Run()
if cmd.ProcessState.Success() {
	fmt.Println(string(stdout))
} else {
	fmt.Println("ERROR!")
	fmt.Println(string(stderr))
}

This is very rough, and from memory, might be that you need to apply small changes, but those should be easily done with an eye on the docs.


PS: I’d be very happy if you not at-mention me right away in the first post, just to make me hurry or get better heard. There are many people on this forum that are able to help. Also I’m still without coffee at the time you posted, which is a state I shouldn’t write code or english in :wink:

If though you quote me from somewhere else, I’m fine with getting at-mentioned.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.