如何检查 Ruby 脚本中的 STDIN 输入? [英] How can you check for STDIN input in a Ruby script?

查看:54
本文介绍了如何检查 Ruby 脚本中的 STDIN 输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查 Ruby 脚本中是否存在 STDIN 输入,就像 mysql 命令一样.如果没有任何内容指向 STDIN,则脚本不应尝试读取 STDIN.

I need to check for the presence of STDIN input in a Ruby script, like the mysql command can. If nothing is being directed to STDIN, then the script should not attempt to read STDIN.

如何以跨平台的方式做到这一点?

How can this be done in a cross-platform way?

推荐答案

Linux 经常这样做:

This is something that's done in Linux a lot:

#!/usr/bin/env ruby

str = (STDIN.tty?) ? 'not reading from stdin' : $stdin.read
puts str

>> $ ruby test.rb 
>> not reading from stdin
>> $ echo "reading from stdin" | ruby test.rb 
>> reading from stdin

这篇关于如何检查 Ruby 脚本中的 STDIN 输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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