How to check if stdin buffer is empty at TCL?

2020-04-17 05:07发布

问题:

With fconfigure you can get and set channel options. -buffering specifies the type of buffering, and by default it is line for stdin.

Is there a way to check if the buffer at stdin is empty or not?


Please see this question: How to check if stdin is pending in TCL?

回答1:

Obviously you could set the channel mode to non-blocking and read from it. If the read returns 0 length then nothing was available. However, I suspect you mean to test for data present but not a complete line given your mentioning of the line buffering there. The fblocked command tests a channel for this. See fblocked(1) for the details but for a line buffered channel this lets you know that an incomplete line is present.

Another useful command when reading stdin, if you are reading interactive script commands is to use the info complete command. With this you can just accumulate lines until info complete returns true then evaluate the whole buffer in one.



回答2:

You can check Tcl's input buffer with chan pending input stdin (requires at least Tcl 8.5). This does not indicate whether the OS has anything in its buffers though; those are checked by trying to read the data (gets or read) or by using a script that triggers off of a readable fileevent, when at least one byte is present. (Well, strictly what is actually promised is that an attempt to read a single byte won't block, but it could be because of an error condition which causes immediate failure. That's the semantics of how OS-level file descriptor readiness works.)

The -buffering option only affects output channels; it's useless on stdin (or any other read-only channel) and has no effect at all. Really. (It is, however, too much trouble to remove.)



回答3:

I know this is an old question but it sparked some research on my end and I found a function called fileevent which calls an event handler when the stream, i.e. stdin, has something in it that can be read. It may be helpful.

Source: http://wiki.tcl.tk/880



标签: buffer tcl stdin