LoginSignup
0
0

More than 5 years have passed since last update.

GoでPythonのsubprocess.call(~, shell=True)みたいにコマンドを実行する

Posted at

Pythonスクリプト内からコマンドを実行する際、subrocess.callshell=Trueを指定すると、argsに渡した文字列がシェルによってそのまま実行されます。

PythonのドキュメントによればUnix系なら/bin/sh、WindowsならCOMSPEC環境変数がシェルとして使われるようなので、Goで同様のことをやる場合は、以下のようになるでしょうか。

main.go
package main

import (
    "os"
    "os/exec"
    "runtime"
)

func callSubprocess(cmdString string) (err error) {
    osname := runtime.GOOS
    var cmd *exec.Cmd
    if osname == "windows" {
        shell := os.Getenv("COMSPEC")
        cmd = exec.Command(shell, "/c", cmdString)
    } else {
        shell := "/bin/sh"
        cmd = exec.Command(shell, "-c", cmdString)
    }
    cmd.Stdout = os.Stdout
    err = cmd.Run()

    return
}

func main() {
    err := callSubprocess("dir")

    if err != nil {
        os.Exit(1)
    }
}
0
0
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
0
0