Golang get command tty output

青春壹個敷衍的年華 提交于 2021-02-08 05:23:23

问题


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.

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

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)

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.

Thanks in advance!


回答1:


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.

You may start with this query.

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

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.

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



来源:https://stackoverflow.com/questions/58032771/golang-get-command-tty-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!