Golang获取命令tty输出 [英] Golang get command tty output

查看:159
本文介绍了Golang获取命令tty输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用go的exec Run命令获取命令输出,当命令'Stdout'字段设置为 os.Stdout 并将错误发送到 os时,该命令非常有用.Stderr .

I'm using go's exec Run command to get command output, which works great when the command 'Stdout' field is set to os.Stdout, and the error is sent to os.Stderr.

我想将输出和错误输出显示到控制台,但我也希望我的程序查看输出是什么.

I want to display the output and the error output to the console, but I also want my program to see what the output was.

然后我创建了自己的Writer类型,将其写入缓冲区并打印到终端.

I then made my own Writer type that did just that, wrote both to a buffer and printed to the terminal.

这就是问题所在:某些应用程序在检测到未写入tty时,会将其输出更改为人类无法读取的内容.因此,当我以后者的方式进行输出时,输出变得难看.(计算机更清洁,人类更难看)

Here's the problem—some applications change their output to something much less readable by humans when it detects it's not writing to a tty. So the output I get changes to something ugly when I do it in the latter way. (cleaner for computers, uglier for humans)

我想知道Go中是否有某种方法可以说服我正在运行的任何命令我是tty,尽管不是 os.Stdout/os.Stderr .我知道可以使用 script bash命令来执行此操作,但是根据Darwin/Linux使用不同的标志,因此我在尝试避免这种情况.

I wanted to know if there was some way within Go to convince whatever command I'm running that I am a tty, despite not being os.Stdout/os.Stderr. I know it's possible to do using the script bash command, but that uses a different flag depending on Darwin/Linux, so I'm trying to avoid that.

提前谢谢!

推荐答案

解决此问题的唯一实用方法是分配

The only practical way to solve this is to allocate a pseudo terminal (PTY) and make your external process use it for its output: since PTY is still a terminal, a process checking whether it's connected to a real terminal thinks it is.

您可以从此查询开始.

github.com/creack/pty 可能是一个很好的起点.

The github.com/creack/ptyis probably a good starting point.

下一步是让实现PTY的程序包实际分配它,并将PTY的另一端"连接到您的自定义编写器.

The next step is to have a package implementing a PTY actually allocate it, and connect "the other end" of a PTY to your custom writer.

(顺便说一句,因为存在 io.MultiWriter ).

(By the way, there's no point in writing a custom "multi writer" as there exist io.MultiWriter).

这篇关于Golang获取命令tty输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆