Unable to see os.environ['COLUMNS']
Tim Chase
python.list at tim.thechases.com
Mon Sep 15 06:52:16 EDT 2008
>> What's the best way to read what seems to be a
>> pseudo-environment variable?
>
> You can't. You need to export the variable in the parent shell
> before it exec's the child:
>
> $ export COLUMNS
>
> $ python -c "import os; print os.environ['COLUMNS']"
> 80
This works well, and also manages to keep up to date across runs
as window-size changes. More importantly, it makes sense (minus
the "why doesn't bash automatically export COLUMNS to subshells"
question, but a little investigation shows I can use "set -a" or
"export COLUMNS" in my .bashrc and everything works).
> Now, on to the question you're about to ask:
>
> Q: How do I find out how big my terminal is from a Python
> program?
You must be one of the folks working with the Python
time-machine. :) (okay, so the intent of my question was pretty
obvious)
> A: You use the TIOCGWINSZ ioctl call on the terminal's file
> descriptor:
>
>>>> import sys,fcntl,termios,struct
>>>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
>>>> struct.unpack('hh',data)
> (24, 80)
>
> There's a more detailed explanation here (including an
> explanation of what the third parameter to ioctl() does, and
> how you detect changes in the window size):
>
> http://mail.python.org/pipermail/python-list/2006-February/365710.html
Thanks, I'll read up on that, as well as investigate ncurses options.
> There's also chance that you'd be better off just using ncurses or
> newt for screen management, but that's another post.
The screen-width is merely for a little output formatting to
determine how many items can fit across. However, given the
opacity of the ioctl() call, it might not hurt to look into using
curses.
Thanks for the pointers,
-tkc
More information about the Python-list
mailing list