【问题标题】:How do I make stdin a tty?如何使标准输入成为 tty?
【发布时间】:2015-02-06 18:32:07
【问题描述】:

有些程序会根据其标准输出是否为 tty 来更改其输出。因此,如果您将它们放入管道或重定向它们,则输出与您的外壳中的输出不同。这是一个例子:

$ touch a b c

# when running ls alone, it places them on one line
$ ls
a b c

# when stdout is not a tty, it places them on their own line
$ ls > output

$ cat output
a
b
c
output

所以,如果我想向某人展示这样的命令应该是什么样子(例如,我正在编写教程),我必须突出显示并复制终端的输出,然后将其保存到文件中。

看来我应该可以做这样的事情:

ls | ttypipe > output

ttypipe 是一个假设程序,当被问及它是否是 tty 时,它的标准输入(以及因此 ls 的标准输出)的响应为 true。

我知道在 Ruby 中,我可以做这样的事情:

require 'pty'         # => true
IO.pipe.map(&:tty?)   # => [false, false]
PTY.open.map(&:tty?)  # => [true, true]

但这是针对子进程,而不是当前进程,因此:

$stdin.tty?  # => false

我可以执行,我想不出影响标准输入文件描述符的方法。

【问题讨论】:

  • $stdin.tty?(什么都不需要,使用 IO#tty?)返回 true

标签: ruby linux unix tty pty


【解决方案1】:

你不能写ttypipe,因为管道就是管道,永远不可能是tty。但是,您可以编写 ttyexec,语法略有不同:

ttyexec ls > output

它将打开一个伪终端,在其中运行ls,并将ls 写入终端的任何内容复制到ttyexec 的标准输出。

你瞧,已经有这样的工具了:script。它会在一个新的隐藏 pty 中打开一个程序来记录与它的交互,但我们可以忽略日志记录部分,只使用它的终端打开属性:

$ touch a b c

$ ls
a  b  c

$ script -q -c 'ls' /dev/null > output

$ cat output 
a  b  c  output

【讨论】:

猜你喜欢
  • 2020-10-28
  • 2013-11-26
  • 2012-12-16
  • 1970-01-01
  • 2022-11-10
  • 2021-01-13
  • 1970-01-01
  • 2022-07-10
  • 1970-01-01
相关资源
最近更新 更多