Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute command which requires input from user

Tags:

go

I want to execute perforce command line "p4" from Go to do the login job. "p4 login" require user to input password.

How can I run a program that requires user's input in Go?

The following code doesn't work.

err  = exec.Command(p4cmd, "login").Run()
if err != nil {
    log.Fatal(err)
}
like image 727
yongzhy Avatar asked Jul 04 '12 01:07

yongzhy


2 Answers

From the os/exec.Command docs:

// Stdin specifies the process's standard input. If Stdin is
// nil, the process reads from the null device (os.DevNull).
Stdin io.Reader

Set the command's Stdin field before executing it.

like image 77
axw Avatar answered Oct 19 '22 04:10

axw


// To run any system commands. EX: Cloud Foundry CLI commands: `CF login`
cmd := exec.Command("cf", "login")

// Sets standard output to cmd.stdout writer
cmd.Stdout = os.Stdout

// Sets standard input to cmd.stdin reader
cmd.Stdin = os.Stdin

cmd.Run()
like image 24
Vidhi Shah Avatar answered Oct 19 '22 03:10

Vidhi Shah