Golang运行命令行程序及输入输出

记录一下!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	cmd := exec.CommandContext(ctx, "./app")
	// 获取stdin
	stdin, _ := cmd.StdinPipe()
	defer stdin.Close()

	var stdout bytes.Buffer
	cmd.Stdout = &stdout

	// 启动程序
	cmd.Start()
	// 等待3秒
	time.Sleep(3 * time.Second)

	// 将输入写入子进程
	stdin.Write([]byte(key + "\n"))

	time.Sleep(2 * time.Second)
	stdin.Write([]byte("\n"))
	// 等待命令执行完成
	cmd.Wait()

	// 获取子进程的输出
	stdinOutput := stdout.String()
	fmt.Println(stdinOutput)