Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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)
    }
}
ocadaruma
Javaを書いています
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away