简体   繁体   中英

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.

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.

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') .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM