LoginSignup
1
1

More than 3 years have passed since last update.

ターミナル上の出力を上書きする

Last updated at Posted at 2019-04-29

https://www.youtube.com/watch?v=aE4eDTUAE70 を追っていたところ、
ターミナルに出力しているハッシュが上書き更新されてて、どうやって出力してるのか気になった。

これ。
fmt.Printf("\r%x", hash)

ただし Go playground でやってみると再現せず。

StackOverflow で理由を発見。
出力先によって違うみたい。
https://stackoverflow.com/questions/15442292/golang-how-to-have-an-inplace-string-that-updates-at-stdout

ターミナルに出力されるという前提がある場合は \r でいけるけど、
stdoutはファイルやパイプに渡されたりするので、ターミナルに出力されることを無条件に前提にしてはダメだよ、という注意付き。

ちなみに Go Playground の場合はこう。
https://play.golang.org/p/b1LlRwxPdu

stdoutがターミナルかをチェックするのには、 https://rosettacode.org/wiki/Check_output_device_is_a_terminal#Go の通り terminal.IsTerminal(int(os.Stdout.Fd())) を使うのが良いらしい。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1