hook into os.Stdout / os.Stderr

217 görüntüleme
İlk okunmamış mesaja atla

Alexander Mills

okunmadı,
19 Eyl 2020 15:39:3319.09.2020
alıcı 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

okunmadı,
19 Eyl 2020 15:59:0519.09.2020
alıcı 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

okunmadı,
20 Eyl 2020 04:08:3220.09.2020
alıcı 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.

Tümünü yanıtla
Yazarı yanıtla
Yönlendir
0 yeni ileti