【问题标题】:How to detect if a Ruby script is running through a shell pipe?如何检测 Ruby 脚本是否通过 shell 管道运行?
【发布时间】:2017-05-04 18:02:39
【问题描述】:

我的问题与此类似:How to detect if my shell script is running through a pipe?。不同之处在于我正在编写的脚本是用 Ruby 编写的。

假设我跑步:

./test.rb

我希望标准输出上的文本带有颜色,但是

./test.rb | cat

我希望去掉颜色代码。

【问题讨论】:

    标签: ruby shell pipe


    【解决方案1】:

    使用$stdout.isatty 或更惯用的$stdout.tty?。我创建了一个小 test.rb 文件来演示,内容:

    puts $stdout.isatty
    

    结果:

    $ ruby test.rb
    true
    
    $ ruby test.rb | cat
    false
    

    参考:https://ruby-doc.org/core/IO.html#method-i-isatty

    【讨论】:

    • 或更惯用的:$stdout.tty?
    【解决方案2】:

    使用IO#stat.pipe?IO#tty? 在 TTY 设备上返回 true。 对于 UNIX 风格的管道返回 false(参见“man 2 pipe”)。

     $ echo "something" | ruby -e 'puts $stdin.stat.pipe?'
    true
     $ echo "something" | ruby -e 'puts $stdin.tty?'
    false
     $ ruby -e 'puts $stdin.tty?'
    true
    

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2010-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多