I want to run an interactive shell script in golang program, such as wrap a "ping 8.8.8.8", "python", "bc", "mysql -H -P -u -p". The golang program should exit when itself finish calling an interactive command,or shell, and leaving spawned interactive with user.
I have tried the "exec.Command("python").Run()", but the golang program just finish and leave nothing to me.
func (h ConnectHandler)ConnectMySQL() {
logrus.Debug("ConnectMySQL, script:",common.CONF.FilePath.MySQLConnectScriptPath)
err :=exec.Command("bash",common.CONF.FilePath.MySQLConnectScriptPath).Run()
if err != nil{
logrus.Errorf("ConnectMySQL failed, exit 1,%s",err)
os.Exit(1)
}
}
Connect the Command's stdin, stdout, and stderr to those of the parent process. Also, supply -c
in exec.Command
to bash
, else bash
will try to run your program as if it's a shell script.
For example launching the interactive Python console:
func main() {
fmt.Println("Before Python shell:")
cmd := exec.Command("bash", "-c", "/usr/bin/python3")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run() // add error checking
fmt.Println("After Python shell")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With