6

I'm writing a terminal program and need to get the size of the TTY I'm using. The Internet seems to suggest this can be done with curses, but I can't seem to find out how in python. I'm trying to avoid using the ROWS and COLUMNS environment variables if possible :)

11

Apparently, the getmaxyx() method is what you need. It returns a (height, width) tuple.

Python reference

Some tutorial

Edit: tutorial link is dead, here's the archived version. And here's the example from that link:

Now lets say we want to draw X's down the diagonal. We will need to know when to stop, so we will need to know the width and the height of the screen. This is done with the stdscr.getmaxyx() function. This function returns a tuple with the (height, width) values.

#!/usr/bin/python

import curses
import time
stdscr = curses.initscr()
curses.cbreak()
curses.noecho()
stdscr.keypad(1)

try:
# Run your code here
    height,width = stdscr.getmaxyx()
    num = min(height,width)
    for x in range(num):
        stdscr.addch(x,x,'X')
    stdscr.refresh()
    time.sleep(3)
finally:
    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()
  • 1
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. – coversnail May 8 '12 at 8:07
  • 1
    Would expect to find this on SO, but nontheless, perfect answer, thanks! Signed up just to +1 this. :) – ArtOfWarfare Feb 9 '15 at 20:51
  • Funny, the tutorial link is now dead. – RandomInsano Feb 5 '17 at 17:05
  • 1
    @RandomInsano edited my answer. I think it was just some random tutorial I found through Google. – Timo Feb 6 '17 at 9:56

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.