Execute a command in Go like Python's subprocess.call (~, shell = True)

If you specify shell = True in subrocess.call when executing a command from within a Python script, the string passed to args will be executed by the shell as it is.

According to Python documentation, / bin / sh for Unix and COMSPEC environment variables for Windows. Seems to be used as a shell, so if you want to do something similar in Go, would it look like this:

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)
	}
}


Recommended Posts

Execute a command in Go like Python's subprocess.call (~, shell = True)
How to execute a command using subprocess in Python
Execute external command in python
Behavior when giving a list with shell = True in subprocess
Hit a command in Python (Windows)
Run shell command / python in R
Remote command that behaves like a local command
[Ubuntu] How to execute a shell script
Execute the COPY command using python's Psycopg
Use Python3's Subprocess.run () in a CGI script
How to pass the execution result of a shell command in a list in Python
How to achieve something like a list of void * (or variant) in Go?
I made an appdo command to execute a command in the context of the app
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook