Best way of finding terminal width/height?

Joel Hedlund joel.hedlund at gmail.com
Thu Feb 9 03:24:27 EST 2006


I realised there was funny indentation mishap in my previus email. My mail prog indented the following line 

    signal.signal(signal.SIGWINCH, report_terminal_size_change)

while in fact in IDLE it's unindented, which makes a lot more sense:

signal.signal(signal.SIGWINCH, report_terminal_size_change)

Sorry about that.

/Joel

Joel Hedlund wrote:
>> You might want to try just setting a flag in the signal handler
>> to see if that prevents the I/O operations on stdin/stdout from
>> being interrupted.
> 
> 
> Tried this:
> 
> <source>
> 
> 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)
> 
> while True:
>    # Do lots of IO (I'm trying to provoke exceptions with signal)
>    open('/a/large/file').read()
>    #raw_input()
>    #sys.stdin.read()
>    #print open('/a/large/file').read()
>       if _bTerminalSizeChanged:
>        update_terminal_size()
>        print terminal_size
> 
> </source>
> 
> As before, the only IO case above that doesn't throw exceptions is the 
> uncommented one.
> 
>> Yup, that's the exception.  Standard practice is to catch it and
>> retry the I/O operation.
> 
> 
> Hmm... I guess it's not that easy to "retry" IO operations on pipes and 
> streams (stdin/stdout in this case)... And I tend to lean pretty heavily 
> on those since I usually write UNIX style text "filters".
> 
> So in case I haven't missed something fundamental I guess my best option 
> is to accept defeat (of sorts :-) and be happy with picking a terminal 
> width at program startup.
> 
> But anyway, it's been really interesting trying this out.
> Thank you Grant (och Jorgen) for all help and tips!
> /Joel



More information about the Python-list mailing list