Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run interactive shell script in golang program

Tags:

go

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)
    }
}
like image 573
Panic Avatar asked Jan 25 '23 06:01

Panic


1 Answers

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")
}
like image 151
Shang Jian Ding Avatar answered Feb 07 '23 16:02

Shang Jian Ding