hook into os.Stdout / os.Stderr

215 views
Skip to first unread message

Alexander Mills

unread,
Sep 19, 2020, 3:39:33 PM9/19/20
to golang-nuts
Forgive me for this pigeon code, I am looking to do something like:

os.Stdout.BeforeWrite(func (){

});

os.Stderr.AfterWrite(func(){

})

so I can hook into the system and clear the terminal before hand, and write a status line, after wards. Is this possible?

Raffaele Sena

unread,
Sep 19, 2020, 3:59:05 PM9/19/20
to Alexander Mills, golang-nuts
You can create your own writer and overwrite os.Stdout/Stderr (just supply your own write method with the appropriate before/after hooks)

Sent from my iPhone

On Sep 19, 2020, at 12:38 PM, Alexander Mills <alexande...@gmail.com> wrote:

Forgive me for this pigeon code, I am looking to do something like:
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/86ecac37-cf19-436c-87ed-3f415ca157c4n%40googlegroups.com.

Axel Wagner

unread,
Sep 20, 2020, 4:08:32 AM9/20/20
to Raffaele Sena, Alexander Mills, golang-nuts
As os.Stdout/os.Stderr are *os.File, not io.Writer, you need to go a step further and use os.Pipe. Something like this:
https://play.golang.org/p/V6ygCmwlsiz
TBH, it's not great to do this. As you can tell from the code, this is pretty complicated and if you want error handling, it gets even more complex. Then there is the problem that writes are not synchronous, which can't really be solved, as you write to an `os.File` (going to the OS directly, so this can't be changed) which can do internal buffering, so the write can return before your spawned goroutine even sees it.

Really, it is better to pass a custom `io.Writer` or something to whatever produces the output you want to modify.

Reply all
Reply to author
Forward
0 new messages