#Print command output as it executes

9 messages · Page 1 of 1 (latest)

jovial sun
#

I'm making a go program which has a feature to get the log from a program, so I need to get the output from a command without the program exiting.

For testing purposes, this is my program (idk if relevant, but) ```py
import time
for x in range(15):
print(x)
time.sleep(1)


For running it, I've tried, but with no success ```go
var cmd = exec.Command("python", "ex.py")
    
    
    out, err := cmd.Output()
    if err != nil {
        println(err.Error())
        return
    }
```, which just waits for it to exit. I've also tried ```go
var cmd = exec.Command("python", "ex.py")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Run()
```, but that just outputs it to terminal, which is good, but I want to set it to an array/string as it outputs
quaint lintel
#

Stdout and Stderr are both io.Writers I believe

#

so you can assign them to a string buffer

jovial sun
quaint lintel
#

bytes.Buffer implements Reader and Writer and has other convenient methods that will let you access its contents

dense groveBOT
#
type Buffer struct {
    // contains filtered or unexported fields
}

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

quaint lintel
#

so you can assign Stdout and Stderr to either the same buffer or seperate ones

#

and then after the command runs you can call String on it, or whatever to get its output

#

(note, you have to provide a pointer to the struct)