株式会社ヴァンデミックシステム

Blog

<スポンサーリンク>

コマンド結果を受け取らず、実行完了まで待機

  • Run
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    err := exec.Command("pwd").Run()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }
}

 

コマンド結果を受け取る

  • Output
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    out, err := exec.Command("pwd").Output()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    // 実行したコマンドの結果を出力
    fmt.Printf("pwd result: %s", string(out))
}

 

標準出力エラーを受け取る

- CombinedOutput

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    out, err := exec.Command("ls", "dummy").CombinedOutput()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    // 実行したコマンドの標準出力+標準エラー出力の内容
    fmt.Printf("ls result: \n%s", string(out))
}

 

コマンド実行終了を待たない

  • start
  • waitとの組み合わせで待つことができる
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("sleep", "10")

    fmt.Println("Command Start.")

    err := cmd.Start()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    //コメント外すと待機する
    //cmd.Wait()

    fmt.Println("Command Exit.")
}

 

参考

 

 

<スポンサーリンク>

コメントを残す

Allowed tags:  you may use these HTML tags and attributes: <a href="">, <strong>, <em>, <h1>, <h2>, <h3>
Please note:  all comments go through moderation.

*

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)