LoginSignup
33
33

More than 5 years have passed since last update.

Goで外部コマンドを実行して出力をリアルタイム表示するサンプル

Posted at

はじめに

外部コマンドを実行して出力をリアルタイム表示するサンプルコマンドを作ってみました。

サンプルコマンドに-vを指定した時は冗長モードでリアルタイム表示しつつ、外部コマンド終了時に標準出力と標準エラー出力の結果を文字列で取得します。

-vを指定しない時は、外部コマンド実行中のリアルタイム表示は無しで、外部コマンド終了時に標準出力と標準エラー出力の結果を文字列で取得するほうだけを行います。

スクリーンショット

tty.gif

実装メモ

ソース: https://github.com/hnakamur/execcommandexample

コマンドを実行して出力を読み取るサンプルはexec.Cmd.StdoutPipe()のExampleにコード例があります。

標準出力と標準エラー出力を両方リアルタイムに呼び出したいので、StdoutPipe()とStderrPipe()を取得して、2つのgoroutineでそれぞれ読みだして出力するようにしました。
https://github.com/hnakamur/execcommandexample/blob/master/main.go#L53-L54

また、最終的な結果を取るためにio.TeeReaderを使ってBufferにも保存しています。
https://github.com/hnakamur/execcommandexample/blob/master/main.go#L45-L47

TeeReaderを使った関係で、verbose=falseのときもReaderからは読み取っておく必要があります。
https://github.com/hnakamur/execcommandexample/blob/3f4f3a2c659323d3ada722961b0439c22bf77467/main.go#L74

カラー表示用の文字列生成は github.com/mgutz/ansiを使いました。

33
33
3

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
33
33