Python curses, pythoncurses

Source: Internet
Author: User
Tags python curses

Python curses, pythoncurses

In python, curses encapsulates the c-language curses and simplifies the complex section of c, such as addstr (), mvaddstr (), and mvwaddstr (), and merges them into an addstr () method.

1. Syntax 1. Open and Close a curses Application

Initialize curses before executing any code. The initialization operation is to call the initscr () function, as shown below. This function returns a window object representing the entire Screen Based on different devices. This window object is usually called stdscr, which is consistent with the C language error.

import cursesstdscr = curses.initscr()

When using curses, screen ECHO is usually disabled to read characters and output only in the appropriate environment. Therefore, you need to call the noecho () method.

curses.noecho()

Applications usually respond immediately, that is, they do not need to press enter to immediately respond. This mode is called the cbreak mode. The opposite common mode is the buffer input mode. The code for enabling the cbreak mode is as follows.

curses.cbreak()

The terminal often returns a special key as a multi-byte escape sequence, such as a cursor key, or a navigation key such as the Page UP and Home keys. Curses can process these sequences once. For example, curses. KEY_LEFT returns a special value. To do this, you must enable the keyboard mode.

stdscr.keypad(1)

It is very easy to close curses, as shown below:

Curses. nocbreak () # disable the character terminal function (terminal only occurs when you press Enter) stdscr. keypad (0) curses. echo () # enable the input echo Function

Call endwin () to restore the default settings

curses.endwin()

The common problem for debugging curses is that the curses application does not reset the terminal to the previous status after it ends, making the terminal a mess. In python, this problem is often caused by code bugs and sending exceptions. For example, if the screen is not displayed after a character is typed on the keyboard, it is very difficult for shell to use.

To avoid this problem, you can import the curses. wrapper module. This function performs initialization, including the above mentioned and color initialization. Then execute the function you provided and reset it. And the called function is written in try-catch.

2. open a new window and pad

Generally, call initscr () to obtain a window object that represents all the screens. However, many programs want to divide the screen into several small windows. In order to re-paint, the work is wiped out independently in small windows. The newwin () function is used to create a new window. You need to specify the window size and return the new window object.

begin_x = 20; begin_y = 7height = 5; width = 40win = curses.newwin(height, width, begin_y, begin_x)

Note: The coordinates are first y and then x. This is different from other coordinate systems, but it is deep-rooted. It is too late to change it when writing.

When you call a method to display or erase text, the effect is not displayed immediately. To reduce the screen re-painting time, curses will first accumulate these operations and display them in a more effective way. For example, if your program displays several characters in the window and then clears the screen, it is unnecessary to send the initial characters because they will not be displayed.

Therefore, curses requires you to use the refresh () function to explicitly specify the re-painting window.

Pad

Pad is a special case of window. The pad can be larger than the display screen. Only a part of the pad is displayed at a time. Creating a pad is simple. You only need to provide width and height. However, to refresh the pad, you must provide the coordinates of some pad displayed on the screen.

pad = curses.newpad(100, 100)#  These loops fill the pad with letters; this is# explained in the next sectionfor y in range(0, 100):    for x in range(0, 100):        try:            pad.addch(y,x, ord('a') + (x*x+y*y) % 26)        except curses.error:            pass#  Displays a section of the pad in the middle of the screenpad.refresh(0,0, 5,5, 20,75)

When multiple windows or pads are used at the same time, the screen will flash when a window or pad is refreshed.

To avoid blinking: Call the noutrefresh () method in each window. Use the refresh () method and then call the doupdate () method.

3. display text

The addscr format is as follows: if there is no coordinate, the character is displayed at the end of the previous operation.

Form Description
StrOrCh Display the stringStrOr characterChAt the current position
StrOrCh,Attr Display the stringStrOr characterCh, Using attributeAttrAt the current position
Y,X,StrOrCh Move to positionY, xWithin the window, and displayStrOrCh
Y,X,StrOrCh,Attr Move to positionY, xWithin the window, and displayStrOrCh, Using attributeAttr

Attribute enables text to be highlighted, such as a black body, underline, reverse order, and color display.

4. attributes and colors

Attributes and description:

Attribute Description
A_BLINK Blinking text
A_BOLD Extra bright or bold text
A_DIM Half bright text
A_REVERSE Reverse-video text
A_STANDOUT The best highlighting mode available
A_UNDERLINE Underlined text

The first line of the screen is reverse-video.

stdscr.addstr(0, 0, "Current mode: Typing mode",              curses.A_REVERSE)stdscr.refresh()

Curses uses the foreground color and background color. You can use the color_pair () method to obtain a pair of colors.

Display a line by color on 1

stdscr.addstr("Pretty text", curses.color_pair(1))stdscr.refresh()

Start_color () initializes 8 base colors: 0: black, 1: red, 2: green, 3: yellow, 4: blue, 5: magenta, 6: cyan, and 7: white.

Init_pair (n, f, B) modifies the color to n, so that f is the foreground color, and B is the background color. The color is black and white, and cannot be changed.

For example, to change color1 to a red text with a white background:

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

Usage:

stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))
5. user input

The getch () method is used to obtain the input again. This method suspends the waiting for user input and displays the echo () method.

Getch () returns an integer between 0 and 255, representing the ASCII value of the input character. Print 255 special characters, such as Page Up and Home.

Code is often written like this

while 1:    c = stdscr.getch()    if c == ord('p'):        PrintDocument()    elif c == ord('q'):        break  # Exit the while()    elif c == curses.KEY_HOME:        x = y = 0

Getstr () gets a string. Limited functions are not commonly used.

curses.echo()            # Enable echoing of characters# Get a 15-character string, with the cursor on the top lines = stdscr.getstr(0,0, 15)
Ii. Example

The Code is as follows:

#-*-Coding: UTF-8-*-import cursesstdscr = curses. initscr () def display_info (str, x, y, colorpair = 2): ''' use the specified colorpair to display the text ''' global stdscr. addstr (y, x, str, curses. color_pair (colorpair) stdscr. refresh () def get_ch_and_continue (): ''' demonstrate press any key to continue ''' global stdscr # Set nodelay. When it is set to 0, it will become blocked waiting for stdscr. nodelay (0) # enter a character ch = stdscr. getch () # reset nodelay so that the console can accept console input in a non-blocking manner, timeout 1 second stdscr. nodelay (1) return Truedef set_win (): ''' console settings ''' global stdscr # Call this method to use the color first. start_color () # Set the text and background color. set two color pair values: 1 and 2 curses. init_pair (1, curses. COLOR_GREEN, curses. COLOR_BLACK) curses. init_pair (2, curses. COLOR_RED, curses. COLOR_BLACK) # Turn off the screen to show curses. noecho () # Do not press enter to confirm curses. cbreak () # Set nodelay so that the console can accept console input in a non-blocking manner, timeout 1 second stdscr. nodelay (1) def unset_win (): ''' console reset ''' global stdstr # restore the default console settings (if not restored, it will cause exit even if the program ends, the console still has no echo) curses. nocbreak () stdscr. keypad (0) curses. echo () # End Window curses. endwin ()
If _ name __= = '_ main _': try: set_win () display_info ('hola, curses! ',) Display_info ('Press any key to continue...',) get_ch_and_continue () failed t Exception, e: raise e finally: unset_win ()

Run: # python testcurses. py

Iii. troubleshooting

Error:

[root@yl-web-test srv]# python curses.pyTraceback (most recent call last):  File "curses.py", line 2, in <module>    import curses  File "/srv/curses.py", line 4, in <module>    stdscr = curses.initscr()AttributeError: 'module' object has no attribute 'initscr'

Cause: because the name of my file is curses. py, and the system uses curses. py, it is first searched from the current directory during python execution, so it cannot be renamed with the system file.

Change the name, for example, testcurses. py.

Refer:

Https://docs.python.org/2/howto/curses.html

 

Starof, the author of this article, is constantly learning and growing because of the changing knowledge. The content of this article is also updated from time to time. To avoid misleading readers and facilitate tracing, Please repost the Source: Ghost.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.