简体   繁体   中英

What does #tty? on STDIN mean / do in ruby?

Reading the ruby docs isn't overly helpful here :

Returns true if ios is associated with a terminal device (tty), false otherwise.

I was hoping to get some additional resources or explanation to help me understand this better.

For context, I'm writing a little command line program that accepts either a file path or piped content into the ruby executable and am using #tty? to determine what is coming in.

Thanks!

Seems like http://www.jstorimer.com/blogs/workingwithcode/7766125-writing-ruby-scripts-that-respect-pipelines supplies the most concise description of what #tty? does:

Ruby's IO#isatty method (aliased as IO#tty?) will tell you whether or not the IO in question is attached to a terminal. Calling it on $stdout, for instance, when it's being piped will return false.

Here is some relevant info that you may find useful:

Background meaning via What do pty and tty mean? :

In UNIX, /dev/tty* is any device that acts like a "teletype", ie, terminal. (Called teletype because that's what we had for terminals in those benighted days.)

In the spirit of the question, here's an example of writing to /dev/tty from http://zetcode.com/lang/rubytutorial/io/ :

#!/usr/bin/ruby

fd = IO.sysopen "/dev/tty", "w"
ios = IO.new(fd, "w")
ios.puts "ZetCode"
ios.close

Look at how grep handles this situation for the traditional UNIX approach: No file specified? Default to $stdin and don't worry about TTY status, maybe someone wants to paste into the terminal. If a filename is specified, read from that and ignore STDIN.

The tty? function is there so you can know if you should send things like ANSI escape codes to colour your output. It's not generally a reliable signal of if someone wants to supply input over STDIN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM