Oliver Bevan
Oliver Bevan

Reputation: 45

How do I get the terminal height (in lines) in Python IDLE Shell?

I'm creating a Hangman game in Python 3.5. I'm trying to create a function to clear the console window, which I can do easily by using os.system("cls") on Windows or os.system("clear") for macOS, Linux etc. However, when running the script in the IDLE Shell, these commands do not work, so instead I am trying to print a series of newlines to hide all the previous content.

I am struggling to find the IDLE Shell height in lines. I've tried os.get_terminal_size()[1] but this gives the error "ValueError: bad file descriptor".

Here is my current code:

def clear():
"""Clears the console window.

Executes the 'cls' command when running on Windows, or 'clear' on
other platforms (e.g. Linux, macOS). IDLE shell cannot clear, so 
prints newlines instead.
"""
if "idlelib.run" in sys.modules:
    # If running in IDLE.
    print("\n" * os.get_terminal_size()[1])
elif platform.system() == "Windows":
    # If running in Windows terminal.
    os.system("cls")
else:
    # If running in other terminals (Linux, macOS)
    os.system("clear")

How would I go about finding the IDLE Shell size in lines? Thanks in advance.

Upvotes: 4

Views: 1236

Answers (3)

user17918267
user17918267

Reputation: 1

In python 3.3+ (text mode only):

>>> import os

>>> os.get_terminal_size()
os.terminal_size(columns=124, lines=52)

also:

>>> os.get_terminal_size().lines
52
>>> os.get_terminal_size()[1]
52

ok

Upvotes: 0

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

You problem is twofold. 1. IDLE was designed, 20 years ago, for developing programs, not for users running them. 2. Where it matters, os and shutil were designed to work with actual text terminals, with a fixed number of lines and columns, or with programs than imitate such. They were were not designed to interact with GUI frameworks. There are separate modules for that.

What you could do.

  1. Have users run your program on the system terminal (the usual default). For development, print something like "\n**clear screen**\n" to signal you, the developer, that the screen would be normally be cleared.

  2. In the IDLE branch, print('\n'*N), where N is, say, 75, which should usually be enough. Or use a smaller number and inform users that you program assumes the window is at most N lines.

  3. Learn enough tkinter to run your program. Clearing the screen is then text.delete('1.0', 'end-1c').

Upvotes: 1

Tim Körner
Tim Körner

Reputation: 385

Well I do not think that is that easy... As you can see here for GUI apps the file handle to the output can be None. That's the reason you can not get the size of the idle window using os.get_terminal_size(). However when you just use a normal cmd terminal you can just use it.

Aside from that I would use shutil.get_terminal_size(). This is the high level function as per this and should normally be used.

Upvotes: 1

Related Questions