go语言与终端交互编程

前段时间用go编程,其中涉及到需要与终端进行交互的操作。写一个简单的demo记录go怎么与终端进行操作

tt.cpp文件

include <iostream>
using namespace std;
int main()
{
    string ch;
    while(1)
    {
        cout<<"please input:";
        cin>>ch;
        cout<<ch<<endl;
    }
    return 0;
}

编译g++ tt.cpp -o tt

 

test.go文件

package main

import (
        "log"
        "os"
        "os/exec"
        "time"

        expect "github.com/Netflix/go-expect"
)

func main() {
        c, err := expect.NewConsole(expect.WithStdout(os.Stdout))
        if err != nil {
                log.Fatal(err)
        }
        defer c.Close()

        cmd := exec.Command("./tt")
        cmd.Stdin = c.Tty()
        cmd.Stdout = c.Tty()
        cmd.Stderr = c.Tty()

        go func() {
                c.ExpectEOF()
        }()

        err = cmd.Start()
        if err != nil {
                log.Fatal(err)
        }

        time.Sleep(time.Second)
        c.Send("Hello\r")
        time.Sleep(time.Second)
        c.Send("world\r")

        err = cmd.Wait()
        if err != nil {
                log.Fatal(err)
        }
}

输入命令 go run test.go 就可以执行看到输出效果了,运行结果截图

展开阅读全文

没有更多推荐了,返回首页