Best way of finding terminal width/height?
Joel Hedlund
joel.hedlund at gmail.com
Tue Feb 7 12:11:57 EST 2006
> You just call the failed read() or write() again. Unless
> there's some way that the read/write partially succeeded and
> you don't have any way to know how many bytes were
> read/written, If that's the case then Python's "file" object
> read and write would appear to be broken by design.
Wow... I tried to set up an example that would fail, and it didn't. It seems the test only fails if I use the keyboard to cram stuff into stdin, and not if stdin is a regular pipe.
Could this perhaps be some kind of misbehavior on behalf of my terminal emulator (GNOME Terminal 2.12.0 in Ubuntulinux 5.10)?
Example follows:
<winch.py>
import signal, os, sys
from terminal_info import get_terminal_size
terminal_size = get_terminal_size()
_bTerminalSizeChanged = False
def report_terminal_size_change(signum, frame):
global _bTerminalSizeChanged
_bTerminalSizeChanged = True
def update_terminal_size():
global _bTerminalSizeChanged, terminal_size
terminal_size = get_terminal_size()
_bTerminalSizeChanged = False
signal.signal(signal.SIGWINCH, report_terminal_size_change)
# Retry IO operations until successful.
io_successful = False
while not io_successful:
try:
s = sys.stdin.read()
io_successful = True
except IOError:
pass
io_successful = False
while not io_successful:
try:
sys.stdout.write(s)
io_successful = True
except IOError:
pass
</winch.py>
Then run the prog and pipe a large chunk of text into stdin, and redirect stdout to a file:
$ cat /a/large/text/file | python winch.py > copy.of.the.large.file
Now, what happens for me is exactly what I wanted. I can resize the window as much as I like, and a diff
$ diff /a/large/text/file copy.of.the.large.file
comes up empty. A perfectly good copy.
However, if I do this instead (try to use keyboard to push stuff into stdin):
$ python winch.py > copy.of.the.large.file
I expect python not to return until I press Ctrl-D on my keyboard, but it does return as soon as I enter more than one line of text and then resize the window (one unterminated line is ok).
Example text to type in:
moo moo
cow cow
As soon as I have typed in something that includes a newline charater through the keyboard and try to resize the terminal, sys.stdin.read() will return whatever I put in no far and no exception raised.
Weird. Could it in fact my terminal that's screwing things up for me?
/Joel
More information about the Python-list
mailing list