Python curses use

Source: Internet
Author: User
Tags ord python curses

Python curses encapsulates the C language curses, simplifying the complex parts of C, such as ADDSTR (), Mvaddstr (), and Mvwaddstr () into a addstr () method.

I. Getting Started with grammar 1. Open and close a curses application

Initialize the curses before any code is executed. The initialization operation is called the INITSCR () function, as follows. The function returns a Window object representing the entire screen depending on the device, which is usually called STDSCR, and is consistent with the C language error.

Import= CURSES.INITSCR ()

Using curses is usually to turn off screen echoing, with the intention of reading the characters only in the appropriate environment for output. This requires calling the NoEcho () method

Curses.noecho ()

The application is generally immediate response, that is, do not need to press ENTER to respond immediately, this mode is called Cbreak mode, the opposite of the usual mode is buffered input mode. Turn on immediate cbreak mode code 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 do a single processing for these sequences, such as curses. Key_left returns a special value. To complete these tasks, you must turn on keyboard mode.

Stdscr.keypad (1)

Closing the curses is very simple, as follows:

Curses.nocbreak ()# Close character terminal function (terminal only occurs when carriage return)# turn on input echo function

Call Endwin () to restore the default settings

Curses.endwin ()

The common problem when debugging curses is that the curses application ends without resetting the terminal to its previous state and messing up the terminal. The problem in Python is often caused by a bug in the code and sending an exception. For example, the keyboard typing character after the screen does not echo, which makes the shell very difficult to use.

To avoid this problem, you can import the Curses.wrapper module. This function does some initialization work, including the above mentioned and the initialization of the color. Then execute the function you provided and finally reset. And the called function is written in Try-catch.

2. Open a new window and pad

Usually call INITSCR () to get a Window object representing the entire screen. But many programs want to divide the screen for several small windows, in order to redraw, to wipe out these work independently in a small window. The Newwin () function is used to create a new window that needs to be given a window size and return the new Windows object.

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

Note : coordinates are passed first y after x. It's different from other coordinate systems, but it's so deep-rooted that it's too late to write.

When a method is called to display or erase text, the effect is not displayed immediately. To reduce the time it takes to redraw the screen, curses accumulates these actions and displays them in a more efficient way. Just like your program shows a few characters in the window and then clears the screen, there's no need to send the initial characters because they won't be displayed.

Therefore, curses requires that you explicitly redraw the window using the Refresh () function.

Pad

Pad is a special case of window. The pad can be larger than the displayed screen, showing only part of the pad at a time. Creating a pad is simple and requires only a wide height. But refreshing the pad needs to provide the coordinates of some pad displayed on the screen.

Pad = curses.newpad (100, 100)#these loops fill the pad with letters;#explained in the next section forYinchRange (0, 100):     forXinchRange (0, 100):        Try: Pad.addch (Y,x, Ord ('a') + (x*x+y*y)% 26)        exceptCurses.error:Pass#displays a section of the the middle of thePad.refresh (0,0, 5, 5, 20,75)

At the same time by multiple windows or multiple pad, there is a problem: the screen will blink when you refresh a window or pad.

Ways to avoid flicker: Call the Noutrefresh () method at each window. Then use the Refresh () method to call the DoUpdate () method last.

3. Display text

ADDSCR different formats are as follows: if there are no coordinates, the characters are displayed at the end of the last operation.

Form Description
str or ch Display the string str or character ch at the current position
str or ch, attr Display the string str or character ch, using attribute attr at the current position
y, x, str or ch Move to position y,x within the window, and display str or ch
y, x, str or ch, attr Move to position y,x within the window, and display str or ch, using attribute attr< /c26>

Attributes can be used to highlight text, such as bold, underline, reverse, and color display.

4. Properties and Colors

Properties 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 Reverse-video displayed.

" Current mode:typing mode " ,              curses. A_reverse) Stdscr.refresh ()

Curses uses the foreground and background colors, which can be obtained by Color_pair () method.

Use color to display one row for 1

Stdscr.addstr ("pretty text", Curses.color_pair (1)) Stdscr.refresh ()

Start_color () initializes the basic colors of 8: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 pair n so that f is the foreground color and b is the background color. Color to 0 days of black and white color, not allowed to change.

For example: Modify Color1 to red text, white background:

Curses.init_pair (1, curses. Color_red, curses. Color_white)

Use:

" RED alert! ", Curses.color_pair (1))
5. User input

Get input once using the Getch () method, this method pauses waiting for user input, which is displayed with the Echo () method.

Getch () returns an integer between 0 and 255 that represents the ASCII value of the input character. Printing 255 is some special characters, such as page Up,home.

Code often writes like this

 while 1:    = stdscr.getch ()    if c = = Ord ('P' ):        PrintDocument ()    elif c = = Ord ('q'):         break  #  Exit the while ()    elif c = = curses. Key_home:        = y = 0

Getstr () gets a string. Because of the limited functionality is not commonly used.

Curses.echo ()            #  Enable echoing of characters#  Get a 15-character string, with the Curs Oron the top line s = Stdscr.getstr (0,0, 15)
Ii. examples

The code is as follows:

#-*-coding:utf-8-*-ImportCURSESSTDSCR=CURSES.INITSCR ()defDisplay_info (str, x, Y, colorpair=2):    " "' Display text using the specified Colorpair" "      Globalstdscr stdscr.addstr (y, X,str, Curses.color_pair (Colorpair)) Stdscr.refresh ()defget_ch_and_continue ():" ""Demo Press any key to continue" "    GlobalSTDSCR#setting Nodelay to 0 will become a blocking waitstdscr.nodelay (0)#Enter a characterCh=Stdscr.getch ()#Resets the Nodelay so that the console can accept console input in a non-blocking manner, timeout 1 secondsStdscr.nodelay (1)    returnTruedefSet_win ():" ""Console Settings" "    GlobalSTDSCR#using color first needs to call this methodCurses.start_color ()#text and background color settings, set two color pair, 1 and 2, respectivelyCurses.init_pair (1, curses. Color_green, curses. Color_black) Curses.init_pair (2, curses. Color_red, curses. Color_black)#Turn off screen echoCurses.noecho ()#no return confirmation required for inputCurses.cbreak ()#set Nodelay, which allows the console to accept console input in a non-blocking manner, time-out of 1 secondsStdscr.nodelay (1)defUnset_win ():" "Console Reset" "    GlobalStdstr#Restore console default settings (if not restored, will cause the console to still not echo even if the program ends exiting)Curses.nocbreak () stdscr.keypad (0) Curses.echo ()#End WindowCurses.endwin ()
if __name__=='__main__': Try: Set_win () Display_info ('Hola, curses!', 0,5) Display_info ('Press any key to continue ...', 0,10) get_ch_and_continue ()exceptexception,e:Raiseefinally: Unset_win ()

Execution: # python testcurses.py

Third, the wrong line

Error:

[[email protected] SRV]#python curses.pyTraceback (most recent): File"curses.py", Line 2,inch<module>ImportCurses File"/srv/curses.py", Line 4,inch<module>STDSCR=CURSES.INITSCR () Attributeerror:'Module'object has no attribute'INITSCR'

Cause: Because my file name is curses.py, and the system is also used Curses.py,python execution when the first search from the current directory, so can not and system files duplicate.

Change the name, for example, renamed Testcurses.py.

Reference:

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

The author starof, because the knowledge itself in the change, the author is also constantly learning and growth, the content of the article is not updated regularly, in order to avoid misleading readers, convenient tracing, please reprint annotated source: http://www.cnblogs.com/starof/p/4703820. HTML has a problem welcome to discuss with me, common progress.

Python curses use

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.