A type of Python application is best to use an interactive user interface that eliminates system overhead or complexity of graphical environments. Interactive text mode program (in Linux / UNIX), such as encapsulated in Python's standard Curses module
The NCURSES library is what you need. In this article, David Mertz discusses usage of Curses in Python. He expounded the Curses environment using sample source code from the front to TXT2HTML programs.
The Curses library (NCURSES) provides a method of controlling the end of the control character screen. Curses is a standard part similar to UNIX, including Linux, and it has been ported to Windows and other systems. The Curses program will run in the XTERM and other windowing console sessions on a plain text system, which makes these applications good portability.
Introduction CursesPython's standard Curses provides a basic interface of the public characteristics of "Glass Teletype" (in the 1970s, the original Curses database just created, it is called CRT) public characteristics. There are many ways to make interactive text mode programs written with Python more clever. These methods are divided into two categories.
On the one hand, some Python modules support all functions of NCURSES (CURSES's super-collection) or SLANG (similarly independent console libraries). Most notably, this has a enhancement library (by appropriate Python module package) allows you to add colors to the interface.
On the other hand, many advanced widget libraries constructing on Curses (or NCURSES / SLANG) add feature such as buttons, menus, scroll, and various public interface devices. If you see an application developed using libraries such as Borland's TurboWindows (DOS Version), you know how attractive in the text mode console. The function in the widget library can be achieved in single use of Curses, but it is also possible to take advantage of the results obtained on the advanced interface. See Resources to find the link of the module mentioned.
This article only involves the characteristics of Curses itself. Since the Curses module is part of the standard release, you don't have to download the support library or other Python modules to find and use it (at least in the Linux or UNIX system). It is useful to understand the basic support provided by Curses, even as the basis for understanding advanced modules. Even without using other modules, use Curses to build beautiful and practical Python text mode applications is also simple. Pre-released instructions Refer to Python 2.0 will include the enhanced version of Curses, but in any case, it should be compatible with the version described here.
Application I will discuss the package written by TXT2HTML (in "Cute Python: My First Web-based Filter Agent", the package written by the text to the HTML conversion program as the test application of this paper. TXT2HTML has several ways of operation. However, in order to be consistent with the purpose of this article, we will study TXT2HTML running from the command line. One way to operate TXT2HTML is to provide a set of command line variables (they explain all aspects of the conversion to be executed) and then run the application as a batch. For occasionally used users, a more friendly user interface provides an interactive selection screen that boots the user traversing the conversion option (providing the visual feedback to the selected option) before performing the actual conversion.
The interface of CURSES_TXT2HTML is based on a common top bar menu, which has a drop and a nested submenu. All menus-related features are "from beginning to" start design on Curses. Although these menus lack some features of more complex Curses package, their basic functions are implemented by only Curses using Curses. This interface also has a simple rolling help box and several users enter fields. The following is a screen snapshot showing the application of a regular layout and a style. X terminal application
Application on the Linux terminal
The basic element of the package Curses application CURSES programming is a window object. The window is an area with a practical physical screen with a addressable cursor, the coordinates of the cursor are related to the window. You can move the window everywhere and you can create and delete the window without affecting other windows. In the window object, the input or output operation occurs on the cursor, which is usually explicitly set by the input or output method, but can also be modified separately.
After initializing Curses, you can modify or completely disable the flow-oriented console input and output in a variety of ways. This is basically the full focus of using Curses. However, once the flow console interaction is changed, if the program is wrong, the Python tracest event will not be displayed in a normal way. Andrew Kuchling uses a good CURSES program top frame to solve this problem (see his tutorial in the reference).
The following template (the same as Kuchling) is retained in the normal command line Python error reporting function:
Python [CURSES] program set code
Import Curses, Traceback
IF __NAME __ == '__ main__':
TRY:
# Ionize curses
STDSCR = Curses.initscr ()
# Turn Off Echoing of Keys, And Enter CBreak Mode,
# Where no buffering is performing on keyboard input INPUT
Curses.noecho ()
Curses.cbreak ()
# In keypad mode, escape sequences for Special Keys
# (like the cursor keys) Will be interpreted and
# a special value like curses.key_left will be returned
Stdscr.Keypad (1)
Main (stdscr) # Enter the main loop
# Set everything back to Normal
Stdscr.KeyPad (0)
Curses.echo ()
Curses.nocbreak ()
Curses.Endwin () # Terminate Curses
Except:
# In Event of Error, Restore Terminal To Sane State.
Stdscr.KeyPad (0)
Curses.echo ()
Curses.nocbreak ()
Curses.Endwin ()
Traceback.print_exc () # Print The Exception
The TRY code block performs some initialization, call the main () function to perform actual work, then perform the final clear. If an error occurs, the Except code block returns the console into the default state and then reports the exception encountered.
Main () event loop now, we study the main () function, see what curses_txt2html do:
CURSES_TXT2HTML.PY Main () function and event loop
DEFMAIN (STDSCR):
# Frame the interface area at fixed VT100 Sizeglobal Screen
Screen = stdscr.subwin (23, 79, 0, 0)
Screen.box ()
Screen.hline (2, 1, curses.acs_hline, 77)
Screen.refresh ()
# Define the topbar menus
FILE_MENU = ("file", "file_func ()")
Proxy_menu = ("Proxy Mode", "Proxy_Func ()")
DOIT_MENU = ("Do It!", "DOIT_FUNC ()")
Help_menu = ("Help", "Help_Func ()")
EXIT_MENU = ("exit", "exit")
# Add the topbar menus to screen object
TOPBAR_MENU ((File_Menu, Proxy_Menu, DOIT_MENU,
HELP_MENU, EXIT_MENU))
# Enter The Topbar Menu Loop
While Topbar_Key_Handler ():
DRAW_DICT ()
It is easy to understand the main () function based on the three parts spaced from the space.
The first part executes the regular settings of the application appearance. In order to establish a pre-period interval between application elements, the interactive area is limited to 80 x 25 VT100 / PC screen size (even if the actual terminal window is larger). The program draws a box around this sub-window and draws the visual offset of the top ran menu using the horizontal line.
The second part establishes the menu used by the application. Functions TOPBAR_MENU () Use some tips to bind the hotkey to the application operation and display the menu with the desired visual properties. Please get the source profile (see Resources) to view all code. Topbar_menu () should be very ordinary. (Welcome to merge it into your own application.) This is very important to bind the hotkey, which is included in the Eval () and the string of the byte group associated with the menu. For example, activating the "File" menu in the above settings will call "EVAL (" File_Func () "). So ask the application definition that the function is called File_Func (), requires it to return a boolean value to indicate whether the application is reached.
The third part is only two lines, but this is the actual operation of the entire application. Functions TOPBAR_KEY_HANDLER () is like its name implied: it is waiting for hyster, and then processes them. The keystroke handler can return the Boolean False value. (If this is the case, the application terminates.) In this application, the key handler is primarily checked in the second paragraph. But even if your Curses application bind key is different from that application, you still have to use a similar event loop. The key part of the handler is likely to use the following line code:
c = screen.getch () # ie KEYPRESS
The call to Draw_Dict () is just a unique code in the event cycle. This function draws a value in several positions in the Screen window. But in the application, you may want to take the following line of code:
Screen.refresh () # redraw the screen w / any new output
Add it to the draw / refresh function (or only to the event loop itself).
Gets the user to enter the Curses application to get all user inputs in the form of key events. We have seen the .getch () method, now let us take a look at the example of the .getch () with other input methods. GetStr (). Here is the abbreviated version of the file_func () function we mentioned (it is activated by the "File" menu). CURSES_TXT2HTML.PY File_Func () function
Deffile_func ():
s = CURS.NEWWIN (5, 10, 2, 1)
s.box ()
S.addstr (1, 2, "i", hotkey_attr)
S.Addstr (1,3, "nput", menu_attr)
S.Addstr (2, 2, "o", hotkey_attr)
S.addstr (2, 3, "UTPUT", MENU_ATTR)
S.Addstr (3, 2, "t", hotkey_attr)
S.Addstr (3, 3, "YPE", MENU_ATTR)
S.Addstr (1, 2, ", hotkey_attr)
S.Refresh ()
C = s.getch ()
IF Cin (ORD ('I'), ORD ('I'), CURSES.KEY_ENTER, 10):
Curses.echo ()
S.RASE ()
Screen.addstr (5,33, "* 43, curses.a_underline)
Cfg_dict ['Source'] = Screen.getstr (5,33)
Curses.noecho ()
Else:
Curses.beep ()
S.RASE ()
Return Continue
This function combines several CURSES features. The first thing it does is to create another window object. Since this new window object is the actual drop-down menu of the "file" selection, the program uses the .box () method to draw a framework. In the window S, the program draws several drop-down menu options. The use of a slightly laborious method highlights the hotkey of each option, which is compared to the rest of the option described. (Please see the Topbar_Menu () in the full source code (see Refigu) to learn a method that can be slightly automatically processed.) The last .AddStr () call moves the cursor to the default menu option. Like the main screen, S.Refresh () actually shows the elements drawn on the window object.
After drawing the drop-down menu, the program uses a simple S.Getch () call to get the user's selection. In the demo application, the menu is only responsive to the hotkey, but does not respond to the arrow keys or the removable highlighting column. These more complex menu features can be built by capturing additional keys and set event cycles in the drop-down menu. But this example is enough to explain this concept.
Next, the program compares the keystrokes just read from various hotkey values. In this case, the case of hotkeys can activate the drop-down menu option and can use Enter to activate the default option. (Curses special key often looks not completely reliable, I found that the actual ASCII value "10" must be added to capture the Enter key.) Please note that if you want to perform a character comparison, then package the string to the ORD () built-in Python function.
When the "Input" option is selected, the program uses the .getstr () method, which provides a field input with the original editing capabilities (you can use the retracted key). The input is terminated by the Enter key, and then the method returns the input value. This value is usually assigned to a variable like in the above example.
In order to pass the input field visually, I use a little skill to add a loop to the area that will occur in the data input. In any case, it is necessary, but it adds a visual effect. Draw the underscore from the following line of code: Screen.Addstr (5, 33, "* 43, Curses.a_underline)
Of course, the program must also remove the underscore, this work is performed by the following line code in the Draw_Dict () refresh function:
Screen.addstr (5,33, "* 43, curses.a_normal)
The techniques that endors here outlined and those used in full application source code (see Refigu) should allow you to get your initial understanding of Curses programming. Please use it to write your application. It is not difficult to use. Tell you a good news. In addition to Python, there are many languages that you can access the Curses library, so you learned the knowledge of the Python Curses module to use in other languages.
If the test, the basic CURSES module does not meet your requirements. The "Reference" section provides a number of modules in the "Reference" section, which adds Curses's features and provides a very good development direction.
Reference
Andrew Kuchling describes the introduction of Curses programming, named Curses Programming with Python. Part of this article is inspired by Kuchling example, although it covers different elements of Curses programming (mainly at higher levels). Please visit the best regular initiator garden to get information about the text-based user interface tools based on Python. Pythonncurses is an enhancement module that supports more ncurses feature compared to Python 1.5.2 Curses. There are some preliminary programs to make NCurses replace Curses in Python 2.0.NCurses. Tinter is a module for the advanced window widgets built on Curses. Tinter support button, text box, dialog, and progress bar. A spare product that is not sufficiently causing public attention (and difficult to capture) NCURSES and other various package combined with SLANG and NEWT and Python Packaging Module Snack. The functionality of SLANG is the same as Curses, and the functionality of Newt is the same as Tinter. Check out some examples of Snack. PCRT is a module for direct ANSI escaping code screens. It writes characters to the specific location of the screen using special color and attributes. It is a low-level interface (even lower than Curses), which can only work on the console that supports ansi escape code (mostly in the escape code), but it is a flashing of text mode applications. good idea. Dialog is a Python package similar to the LinuxDialog utility. Utilities (and its Python Packaging) can create "YES / NO", menu, input, message text, information checklist, and radio list dialog. If there is no platform problem, you can use this utility and module to quickly complete a lot of work (of course, the target Linux release must have Dialog). Download the files used and mentioned in this article.