• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
思念以南
博客园    首页    新随笔    联系   管理    订阅  订阅

cmd命令交互

被测试端

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main()  {
	input := bufio.NewScanner(os.Stdin)
	fmt.Println("999")
	for input.Scan() {
		line := input.Text()

		// 输入bye时 结束
		if line == "exit" {
			fmt.Println("结束")
			break
		}
		if line == "888888888888"{
			fmt.Println("99999999999999999999")
		}
		fmt.Println()
		// 更新key对应的val 新key对应的val是默认0值
	}
}

测试端

package main

import (
	"bufio"
	"fmt"
	"io"
	"os/exec"
	"strings"
)

//func main() {
//	ctx, cancel := context.WithCancel(context.Background())
//	cmd := exec.CommandContext(ctx, "F:\\桌面\\go_frame_\\cmd_close\\Test\\AAAA.exe",">>","ssss.txt")
//	cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
//	cmd.Stdout = os.Stdout
//
//	cmd.Start()
//
//	cmd.Wait()
//	cancel()
//	fmt.Println("退出程序中...", cmd.Process.Pid)
//}

func main(){
	cmd0 := exec.Command("F:\\桌面\\go_frame_\\cmd_close\\Test\\test.exe")
	stdout0 , err := cmd0.StdoutPipe() // 获取命令输出内容
	Stdin0 , err := cmd0.StdinPipe()
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := cmd0.Start(); err != nil {  //开始执行命令
		fmt.Println(err)
		return
	}
	useBufferIO := false
	if !useBufferIO {
		//var outputBuf0 bytes.Buffer
		for {
			tempoutput := make([]byte, 256)
			n, err := stdout0.Read(tempoutput)
			if err != nil {
				if err == io.EOF {  //读取到内容的最后位置
					break
				} else {
					fmt.Println(err)
					return
				}
			}
			if n > 0 {
				if strings.ReplaceAll(string(tempoutput[:n]),"\n","") == "999"{
					Stdin0.Write([]byte("888888888888\n"))
				}
				if strings.ReplaceAll(string(tempoutput[:n]),"\n","") == "99999999999999999999"{
					Stdin0.Write([]byte("exit\n"))
				}
				fmt.Println(string(tempoutput[:n]))
				//outputBuf0.Write(tempoutput[:n])
			}
		}
		//fmt.Println(outputBuf0.String())
	} else {
		outputbuf0 := bufio.NewReader(stdout0)
		touput0 , _ , err := outputbuf0.ReadLine()
		if err != nil {
			return
		}
		fmt.Println(string(touput0))
	}
}
posted @ 2022-05-10 14:48  思念以南  阅读(286)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3