Reputation: 117
I have been looking around and can't find another question like this for golang.
Is there a way in golang to open a second console / terminal window and send output to it? I basically want to use one terminal for typing in, and the other to have a constant feed of information that will update in the window whenever the program wants, so I don't want to overwrite what a user is currently typing into the first terminal.
Update:
I have been working on some ideas, and with the exec function, you can run terminal commands, such as the windows "start" function, which opens another terminal and. This is as far as I have made it, now I just need to add a pipe so that the executable "node.exe" will read from it. This apparently is done using the cmd structure in the exec library. I will update, once I get it all i'll post my answer.
package main
import (
"log"
"os/exec"
)
func main(){
cmd := exec.Command("cmd","/C","start","node.exe")
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
for i := 0; i < 100; i++{
log.Println(i)
}
}
This runs node.exe in another terminal, meanwhile it loops through and prints 0-99 to the current terminal
Upvotes: 5
Views: 7586
Reputation: 45287
To clarify, this "open a new console window" seems very OS-specific.
That stated, why not just output logging information to a file and then open a new window and run tail
on that file?
In general, if you're going to have important logging information, it should go to a file. So that part is just good practice to start with. And once you have that log file, running tail
on the file seems perfectly reasonable.
What you're basically building here is a "client/server" pattern. The norm for this behaviour is to provide a "server" program and then connect to it via a "client" program. Just take a look at MongoDB or Redis or MySQL, they ship with some daemon that runs the server and a separate client.
Based on your description, you're trying to do both at once and make that the default behaviour. Even if this works, it's going to seem weird to anyone else trying to use the program. And you'll need to handle weird cases. Like what happens if I fork the "server" portion (logging window) and then visit that window and hit CTRL+C
? Does that kill the server? What happens to the client in the first window?
Trying to do 2 in 1 is going to be messy even if you manage to make it work.
Upvotes: 2