### Example Test Script Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/writing-tests.html A trivial example demonstrating how to use TEST_SETTINGS and run an application with fork=False for testing. ```APIDOC ## Example Test Script ### Description This example shows how to set `TEST_INPUT` and `CONTINUE_AFTER_TEST_INPUT`, and run the application with `fork=False`. ### Code ```python #!/usr/bin/python import curses import npyscreen npyscreen.TEST_SETTINGS['TEST_INPUT'] = [ch for ch in 'This is a test'] npyscreen.TEST_SETTINGS['TEST_INPUT'].append(curses.KEY_DOWN) npyscreen.TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT'] = True class TestForm(npyscreen.Form): def create(self): self.myTitleText = self.add(npyscreen.TitleText, name="Events (Form Controlled):", editable=True) class TestApp(npyscreen.StandardApp): def onStart(self): self.addForm("MAIN", TestForm) if __name__ == '__main__': A = TestApp() A.run(fork=False) # 'This is a test' will appear in the first widget, as if typed by the user. ``` ``` -------------------------------- ### Install npyscreen Source: https://github.com/npcole/npyscreen/blob/master/webpage/index.html Commands for installing the library via setup script or easy_install. ```bash python setup.py install ``` ```bash easy_install npyscreen ``` -------------------------------- ### Complete npyscreen Application Example Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt A comprehensive example demonstrating form creation, custom exit logic, and application startup within npyscreen. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def afterEditing(self): self.parentApp.setNextForm(None) def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') class MyApplication(npyscreen.NPSAppManaged): def onStart(self): self.addForm('MAIN', myEmployeeForm, name='New Employee') # A real application might define more forms here....... if __name__ == '__main__': TestApp = MyApplication().run() ``` -------------------------------- ### BufferPager usage example Source: https://github.com/npcole/npyscreen/blob/master/docs/source/widgets-multiline.md Example of the BufferPager widget usage as referenced in the documentation. ```python * ``` -------------------------------- ### AddressBookApplication Setup in npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/example-addressbk.html This snippet demonstrates the setup of the main application class, AddressBookApplication, which inherits from npyscreen.NPSAppManaged. It initializes the database and adds the necessary forms to the application. ```python class AddressBookApplication(npyscreen.NPSAppManaged): def onStart(self): self.myDatabase = AddressDatabase() self.addForm("MAIN", RecordListDisplay) self.addForm("EDITRECORDFM", EditRecord) if __name__ == '__main__': myApp = AddressBookApplication() myApp.run() ``` -------------------------------- ### npyscreen Options and Option Lists Example Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md An example demonstrating the use of options and option lists within a npyscreen application for configuration or choices. ```python class MyFormWithOptions(npyscreen.Form): def create(self): self.options = [ ('Option 1', 'value1'), ('Option 2', 'value2'), ] self.add_widget(npyscreen.TitleSelectOne, name='Choose an option:', values=self.options) class MyAppWithOptions(npyscreen.NPSApp): def onStart(self): self.addForm('MAIN', MyFormWithOptions, name='Options Example') if __name__ == '__main__': app = MyAppWithOptions() app.run() ``` -------------------------------- ### Basic npyscreen Application Example Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md A simple example demonstrating the fundamental structure of an npyscreen application, including creating a form and adding widgets. ```python import npyscreen class MyForm(npyscreen.Form): def after_creation(self): self.add_widget(npyscreen.TitleText, name='My Text:', value='Default Value') class MyApp(npyscreen.NPSApp): def onStart(self): self.addForm('MAIN', MyForm, name='My Application') if __name__ == '__main__': app = MyApp() app.run() ``` -------------------------------- ### Run a trivial test application Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/writing-tests.txt A complete example demonstrating how to inject keystrokes and run an application without forking. ```python #!/usr/bin/python import curses import npyscreen npyscreen.TEST_SETTINGS['TEST_INPUT'] = [ch for ch in 'This is a test'] npyscreen.TEST_SETTINGS['TEST_INPUT'].append(curses.KEY_DOWN) npyscreen.TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT'] = True class TestForm(npyscreen.Form): def create(self): self.myTitleText = self.add(npyscreen.TitleText, name="Events (Form Controlled):", editable=True) class TestApp(npyscreen.StandardApp): def onStart(self): self.addForm("MAIN", TestForm) if __name__ == '__main__': A = TestApp() A.run(fork=False) # 'This is a test' will appear in the first widget, as if typed by the user. ``` -------------------------------- ### Custom Multiselect Widget Example Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Provides an example of creating a custom multiselect widget, likely for specialized selection needs. ```python class MyCustomMultiSelect(npyscreen.MultiSelect): def get_new_value(self): # Custom logic for getting new value return super().get_new_value() ``` -------------------------------- ### Setting up Color in npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Demonstrates the basic setup for enabling and using color within a npyscreen application. ```python import npyscreen npyscreen.enableColor() # Further color configuration can follow ``` -------------------------------- ### Application Setup and Execution Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/muttlike.txt Set up the main application class to instantiate and configure the custom form. This includes setting status line values, initializing data, and running the form's edit loop. ```python class TestApp(npyscreen.NPSApp): def main(self): F = FmSearchActive() F.wStatus1.value = "Status Line " F.wStatus2.value = "Second Status Line " F.value.set_values([str(x) for x in range(500)]) F.wMain.values = F.value.get() F.edit() if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### Complete NPSAppManaged Application Example Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html A complete example demonstrating an NPSAppManaged application with a custom form that includes logic to exit the application after editing. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def afterEditing(self): self.parentApp.setNextForm(None) def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') class MyApplication(npyscreen.NPSAppManaged): def onStart(self): self.addForm('MAIN', myEmployeeForm, name='New Employee') # A real application might define more forms here....... if __name__ == '__main__': TestApp = MyApplication().run() ``` -------------------------------- ### Basic NPSAppManaged Setup Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt Initial structure for an application managed by the NPSAppManaged class. ```python import npyscreen class MyApplication(npyscreen.NPSAppManaged): pass if __name__ == '__main__': TestApp = MyApplication().run() print "All objects, baby." ``` -------------------------------- ### Demonstrate Option Persistence Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/options.html This example demonstrates how to store specified options in a file between program invocations. It utilizes npyscreen's option handling and file persistence capabilities. ```python #!/usr/bin/env python ``` -------------------------------- ### Implement a Test Application Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/writing-tests.html A complete example demonstrating how to inject keystrokes into an npyscreen application and disable forking for testing. ```python #!/usr/bin/python import curses import npyscreen npyscreen.TEST_SETTINGS['TEST_INPUT'] = [ch for ch in 'This is a test'] npyscreen.TEST_SETTINGS['TEST_INPUT'].append(curses.KEY_DOWN) npyscreen.TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT'] = True class TestForm(npyscreen.Form): def create(self): self.myTitleText = self.add(npyscreen.TitleText, name="Events (Form Controlled):", editable=True) class TestApp(npyscreen.StandardApp): def onStart(self): self.addForm("MAIN", TestForm) if __name__ == '__main__': A = TestApp() A.run(fork=False) # 'This is a test' will appear in the first widget, as if typed by the user. ``` -------------------------------- ### Full Form Implementation Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt Complete example of a custom form integrated with the npyscreen wrapper. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleText, name='Department') self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') def myFunction(*args): F = myEmployeeForm(name = "New Employee") F.edit() return "Created record for " + F.myName.value if __name__ == '__main__': print npyscreen.wrapper_basic(myFunction) ``` -------------------------------- ### Full application with selection widget Source: https://github.com/npcole/npyscreen/blob/master/docs/source/application-structure.md A complete example integrating the TitleSelectOne widget into a custom Form. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') def myFunction(*args): F = myEmployeeForm(name = "New Employee") F.edit() return "Created record for " + F.myName.value if __name__ == '__main__': print npyscreen.wrapper_basic(myFunction) ``` -------------------------------- ### Create and Display Options in Npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/options.txt This example demonstrates how to create an OptionList, populate it with various Option types, reload existing options from a file, display them in a Form using OptionListDisplay, and save them back to a file. ```python #!/usr/bin/env python # encoding: utf-8 import npyscreen class TestApp(npyscreen.NPSApp): def main(self): Options = npyscreen.OptionList() # just for convenience so we don't have to keep writing Options.options options = Options.options options.append(npyscreen.OptionFreeText('FreeText', value='', documentation="This is some documentation.")) options.append(npyscreen.OptionMultiChoice('Multichoice', choices=['Choice 1', 'Choice 2', 'Choice 3'])) options.append(npyscreen.OptionFilename('Filename', )) options.append(npyscreen.OptionDate('Date', )) options.append(npyscreen.OptionMultiFreeText('Multiline Text', value='')) options.append(npyscreen.OptionMultiFreeList('Multiline List')) try: Options.reload_from_file('/tmp/test') except FileNotFoundError: pass F = npyscreen.Form(name = "Welcome to Npyscreen",) ms = F.add(npyscreen.OptionListDisplay, name="Option List", values = options, scroll_exit=True, max_height=None) F.edit() Options.write_to_file('/tmp/test') if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### Form with Selection Widget Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt Contextual example of a form utilizing the TitleSelectOne widget. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') def myFunction(*args): F = myEmployeeForm(name = "New Employee") F.edit() return "Created record for " + F.myName.value if __name__ == '__main__': print npyscreen.wrapper_basic(myFunction) ``` -------------------------------- ### Use a Custom Form Class Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html Instantiate and use a custom form class. The example shows how to create an instance of 'myEmployeeForm', edit it, and retrieve values from its widgets. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleText, name='Department') self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') def myFunction(*args): F = myEmployeeForm(name = "New Employee") F.edit() return "Created record for " + F.myName.value if __name__ == '__main__': print npyscreen.wrapper_basic(myFunction) ``` -------------------------------- ### Mutt-like Form Example Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Illustrates the creation of a form with a layout and behavior similar to the Mutt email client, often used for displaying lists or messages. ```python class MuttForm(npyscreen.Form): def create(self): self.add_widget(npyscreen.TitleMultiLine, name='Messages:', values=['Message 1', 'Message 2', 'Message 3']) self.add_widget(npyscreen.ButtonPress, name='OK', when_pressed_function=self.parent.switchForm_no_change) class MyAppMutt(npyscreen.NPSApp): def onStart(self): self.addForm('MAIN', MuttForm, name='Mutt-like Form') if __name__ == '__main__': app = MyAppMutt() app.run() ``` -------------------------------- ### Using npyscreen wrapper_basic Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html Demonstrates the basic framework for a simple npyscreen application using the wrapper_basic function to manage the curses environment. This is a starting point for applications that don't require complex form management. ```python import npyscreen def myFunction(*args): pass if __name__ == '__main__': npyscreen.wrapper_basic(myFunction) print "Blink and you missed it!" ``` -------------------------------- ### Complete npyscreen Form with TitleSelectOne Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html This example shows a complete npyscreen form including TitleText, TitleSelectOne, and TitleDateCombo widgets. It defines a form class and a function to run it using wrapper_basic. ```python import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') def myFunction(\*args): F = myEmployeeForm(name = "New Employee") F.edit() return "Created record for " + F.myName.value if __name__ == '__main__': print npyscreen.wrapper_basic(myFunction) ``` -------------------------------- ### Example _handlers Dictionary Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/keybindings.html This dictionary maps user key presses to specific handler methods within an npyscreen object. It supports various key representations including curses constants and control character notations. ```python { curses.ascii.NL: self.h_exit_down, curses.ascii.CR: self.h_exit_down, curses.ascii.TAB: self.h_exit_down, curses.KEY_DOWN: self.h_exit_down, curses.KEY_UP: self.h_exit_up, curses.KEY_LEFT: self.h_exit_left, curses.KEY_RIGHT: self.h_exit_right, "^P": self.h_exit_up, "^N": self.h_exit_down, curses.ascii.ESC: self.h_exit_escape, curses.KEY_MOUSE: self.h_exit_mouse, } ``` -------------------------------- ### NPS Application with Search Form Source: https://github.com/npcole/npyscreen/blob/master/docs/source/muttlike.md This TestApp demonstrates how to instantiate and run the FmSearchActive form. It initializes the form, sets status line values, populates the main widget with data, and starts the application's main loop. ```python class TestApp(npyscreen.NPSApp): def main(self): F = FmSearchActive() F.wStatus1.value = "Status Line " F.wStatus2.value = "Second Status Line " F.value.set_values([str(x) for x in range(500)]) F.wMain.values = F.value.get() F.edit() if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### Create a basic form with input widgets Source: https://github.com/npcole/npyscreen/blob/master/webpage/index.html Demonstrates initializing a form, adding text input widgets, and capturing user input. ```python MyForm = Form() usrn_box = MyForm.add_widget(TitleText, name="Your name:") internet = MyForm.add_widget(TitleText, name="Your favourite internet page:") MyForm.edit() # usrn_box.value and internet.value now hold the user's answers. ``` -------------------------------- ### Slider translate_value Method Example Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/widgets-general.html Example of subclassing Slider and overloading the _translate_value method to format the displayed label. Ensures the generated string is of a fixed length. ```python stri = "%s / %s" %(self.value, self.out_of) l = (len(str(self.out_of)))\*2+4 stri = stri.rjust(l) return stri ``` -------------------------------- ### Form.edit Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/form-objects.html Starts interactive editing of form widgets. ```APIDOC ## Form.edit() ### Description Allows the user to interactively edit the value of each widget. This is considered an internal API call and should be avoided if using the NPSAppManaged class. ``` -------------------------------- ### File Selection Dialog Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Demonstrates how to open a file selection dialog for the user to choose a file. ```python selected_file = npyscreen.selectFile() ``` -------------------------------- ### Create and Display Options in Npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/source/options.md Demonstrates creating an OptionList with various option types, loading from and writing to a file, and displaying them in a form using OptionListDisplay. Ensure the file path for saving/loading options is accessible. ```python #!/usr/bin/env python # encoding: utf-8 import npyscreen class TestApp(npyscreen.NPSApp): def main(self): Options = npyscreen.OptionList() # just for convenience so we don't have to keep writing Options.options options = Options.options options.append(npyscreen.OptionFreeText('FreeText', value='', documentation="This is some documentation.")) options.append(npyscreen.OptionMultiChoice('Multichoice', choices=['Choice 1', 'Choice 2', 'Choice 3'])) options.append(npyscreen.OptionFilename('Filename', )) options.append(npyscreen.OptionDate('Date', )) options.append(npyscreen.OptionMultiFreeText('Multiline Text', value='')) options.append(npyscreen.OptionMultiFreeList('Multiline List')) try: Options.reload_from_file('/tmp/test') except FileNotFoundError: pass F = npyscreen.Form(name = "Welcome to Npyscreen",) ms = F.add(npyscreen.OptionListDisplay, name="Option List", values = options, scroll_exit=True, max_height=None) F.edit() Options.write_to_file('/tmp/test') if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### NPSAppManaged Application Control Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-objects.html Methods for managing the application lifecycle, starting the main loop, and controlling form navigation. ```APIDOC ## NPSAppManaged.run() ### Description Activates the default form (id 'MAIN') and starts the application main loop. ### Method Method call ## NPSAppManaged.setNextForm(formid) ### Description Sets the next form to be displayed after the current form's edit loop exits. ### Parameters #### Path Parameters - **formid** (string) - Required - The identifier of the form to switch to. ## NPSAppManaged.switchForm(formid) ### Description Immediately stops editing the current form and switches to the specified form. ### Parameters #### Path Parameters - **formid** (string) - Required - The identifier of the form to switch to. ## NPSAppManaged.switchFormPrevious() ### Description Immediately switches to the previous form in the navigation history. ``` -------------------------------- ### Run NPSAppManaged Application Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-objects.html Starts the main loop of an NPSAppManaged application. Ensures the default form, identified as 'MAIN', is activated. ```python Application.run() ``` -------------------------------- ### Configure SimpleGrid Constructor Arguments Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/widgets-general.txt Initialization parameters for customizing the layout and behavior of SimpleGrid widgets. ```python columns = None column_width = None, col_margin=1, row_height = 1, values = None always_show_cursor = False select_whole_line = False (new in version 4.2) ``` -------------------------------- ### Define a Multiline Checkbox Widget Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/widgets-general.txt Example of creating a custom multiline checkbox widget by subclassing `npyscreen.MultiSelect` and specifying `npyscreen.CheckBoxMultiline` as the contained widget. ```python class MultiSelectWidgetOfSomeKind(npyscreen.MultiSelect): _contained_widgets = npyscreen.CheckBoxMultiline _contained_widget_height = 2 def display_value(self, vl): # this function should return a list of strings. ``` -------------------------------- ### Implement a full application with NPSApp Source: https://github.com/npcole/npyscreen/blob/master/docs/source/introduction.md Shows how to structure a more complex application using the NPSApp framework, including various widget types and interaction handling. ```python #!/usr/bin/env python # encoding: utf-8 import npyscreen class TestApp(npyscreen.NPSApp): def main(self): # These lines create the form and populate it with widgets. # A fairly complex screen in only 8 or so lines of code - a line for each control. F = npyscreen.Form(name = "Welcome to Npyscreen",) t = F.add(npyscreen.TitleText, name = "Text:",) fn = F.add(npyscreen.TitleFilename, name = "Filename:") fn2 = F.add(npyscreen.TitleFilenameCombo, name="Filename2:") dt = F.add(npyscreen.TitleDateCombo, name = "Date:") s = F.add(npyscreen.TitleSlider, out_of=12, name = "Slider") ml = F.add(npyscreen.MultiLineEdit, value = """try typing here!\nMutiline text, press ^R to reformat.\n""", max_height=5, rely=9) ms = F.add(npyscreen.TitleSelectOne, max_height=4, value = [1,], name="Pick One", values = ["Option1","Option2","Option3"], scroll_exit=True) ms2= F.add(npyscreen.TitleMultiSelect, max_height =-2, value = [1,], name="Pick Several", values = ["Option1","Option2","Option3"], scroll_exit=True) # This lets the user interact with the Form. F.edit() print(ms.get_selected_objects()) if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### Basic npyscreen Application Structure Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html A minimal npyscreen application structure using NPSAppManaged for managing forms and a simple MainForm with a TitleText widget. This serves as a starting point for most new applications. ```python import npyscreen # This application class serves as a wrapper for the initialization of curses # and also manages the actual forms of the application class MyTestApp(npyscreen.NPSAppManaged): def onStart(self): self.registerForm("MAIN", MainForm()) # This form class defines the display that will be presented to the user. class MainForm(npyscreen.Form): def create(self): self.add(npyscreen.TitleText, name = "Text:", value= "Hellow World!" ) def afterEditing(self): self.parentApp.setNextForm(None) if __name__ == '__main__': TA = MyTestApp() TA.run() ``` -------------------------------- ### Create a simple form with npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/introduction.txt Demonstrates the basic usage of Form and widget addition to capture user input. ```python MyForm = Form() usrn_box = MyForm.add_widget(TitleText, name="Your name:") internet = MyForm.add_widget(TitleText, name="Your favourite internet page:") MyForm.edit() # usrn_box.value and internet.value now hold the user's answers. ``` -------------------------------- ### Customize Grid Cell Appearance with custom_print_cell Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/widgets-general.txt Override `custom_print_cell` to change cell attributes based on content. This example sets text color to 'DANGER', 'GOOD', or 'DEFAULT' based on 'FAIL' or 'PASS' values. ```python class MyGrid(npyscreen.GridColTitles): # You need to override custom_print_cell to manipulate how # a cell is printed. In this example we change the color of the # text depending on the string value of cell. def custom_print_cell(self, actual_cell, cell_display_value): if cell_display_value =='FAIL': actual_cell.color = 'DANGER' elif cell_display_value == 'PASS': actual_cell.color = 'GOOD' else: actual_cell.color = 'DEFAULT' ``` -------------------------------- ### Create and Display a Basic Form Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html Use this to create a simple form with a name and display it for user interaction. Requires the npyscreen library. ```python import npyscreen def myFunction(*args): F = npyscreen.Form(name='My Test Application') F.edit() if __name__ == '__main__': npyscreen.wrapper_basic(myFunction) print "Blink and you missed it!" ``` -------------------------------- ### Implementing TitleSelectOne Widget Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt Configuring a selection widget with specific height and scroll behavior. ```python self.myDepartment = self.add(npyscreen.TitleSelectOne, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3'], scroll_exit = True # Let the user move out of the widget by pressing the down arrow instead of tab. Try it without # to see the difference. ) ``` -------------------------------- ### Widget Constructor Arguments Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/widgets.html Explains the various arguments that can be passed when creating a widget instance within a npyscreen Form. ```APIDOC ## Widget Constructor Arguments ### Description Arguments used to configure widgets when they are added to a Form. ### Parameters #### Constructor Arguments - **name** (string) - Optional - Used as the label for the widget. - **relx** (integer) - Optional - Relative X-coordinate for widget positioning. Negative values position relative to the right edge. - **rely** (integer) - Optional - Relative Y-coordinate for widget positioning. Negative values position relative to the bottom edge. - **width** (integer) - Optional - Specifies the width of the widget. - **height** (integer) - Optional - Specifies the height of the widget. - **max_width** (integer) - Optional - Maximum width the widget can occupy. Preferred over `width` for flexible sizing. - **max_height** (integer) - Optional - Maximum height the widget can occupy. Preferred over `height` for flexible sizing. - **value** (any) - Optional - The initial value of the widget. - **values** (list) - Optional - Initial list of selectable values for widgets that offer choices. - **editable** (boolean) - Optional - Defaults to True. Determines if the user can edit the widget's value. - **hidden** (boolean) - Optional - Defaults to False. Determines if the widget is visible. - **color** (string) - Optional - Hint for the color scheme of the widget. - **labelColor** (string) - Optional - Hint for the color scheme of the widget's label. - **scroll_exit** (boolean) - Optional - If True, allows moving to the next/previous widget from the first/last item of a multi-line widget. - **slow_scroll** (boolean) - Optional - If True, multi-line widgets scroll one line at a time. - **exit_left** (boolean) - Optional - Allows exiting the widget using the left arrow key. - **exit_right** (boolean) - Optional - Allows exiting the widget using the right arrow key. ``` -------------------------------- ### Example _complex_handlers Structure Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/keybindings.html This list contains pairs of test functions and dispatch functions for handling key presses not found in the _handlers dictionary. The test function must return True for the dispatch function to be executed. ```python (test_func, dispatch_func) ``` -------------------------------- ### Initialize a basic curses wrapper Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/application-structure.txt The wrapper_basic function handles the initialization and cleanup of the curses environment. ```python import npyscreen def myFunction(*args): pass if __name__ == '__main__': npyscreen.wrapper_basic(myFunction) print "Blink and you missed it!" ``` -------------------------------- ### Complex npyscreen Form with Multiple Widgets Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/introduction.html Illustrates the creation of a more complex npyscreen form with various widget types including text, filename, date, slider, multiline text, and selection options. This example is suitable for building feature-rich terminal interfaces. ```python #!/usr/bin/env python # encoding: utf-8 import npyscreen class TestApp(npyscreen.NPSApp): def main(self): # These lines create the form and populate it with widgets. # A fairly complex screen in only 8 or so lines of code - a line for each control. F = npyscreen.Form(name = "Welcome to Npyscreen",) t = F.add(npyscreen.TitleText, name = "Text:") fn = F.add(npyscreen.TitleFilename, name = "Filename:") fn2 = F.add(npyscreen.TitleFilenameCombo, name="Filename2:") dt = F.add(npyscreen.TitleDateCombo, name = "Date:") s = F.add(npyscreen.TitleSlider, out_of=12, name = "Slider") ml = F.add(npyscreen.MultiLineEdit, value = """try typing here!\nMutiline text, press ^R to reformat.\n""", max_height=5, rely=9) ms = F.add(npyscreen.TitleSelectOne, max_height=4, value = [1,], name="Pick One", values = ["Option1","Option2","Option3"], scroll_exit=True) ms2= F.add(npyscreen.TitleMultiSelect, max_height =-2, value = [1,], name="Pick Several", values = ["Option1","Option2","Option3"], scroll_exit=True) # This lets the user interact with the Form. F.edit() print(ms.get_selected_objects()) if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### Add test input via convenience functions Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/writing-tests.txt Helper functions to populate the TEST_INPUT list. ```python npyscreen.add_test_input_from_iterable(iterable) ``` ```python npyscreen.add_test_input_ch(ch) ``` -------------------------------- ### Add TitleSelectOne Widget Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-structure.html Use TitleSelectOne to present a list of options. Set max_height to limit its screen space. scroll_exit=True allows exiting the widget with the down arrow. ```python self.myDepartment = self.add(npyscreen.TitleSelectOne, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3'], scroll_exit = True # Let the user move out of the widget by pressing the down arrow instead of tab. Try it without # to see the difference. ) ``` -------------------------------- ### Convenience Functions Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/writing-tests.txt Helper functions to manage test input configuration. ```APIDOC ## Function: npyscreen.add_test_input_from_iterable(iterable) ### Description Adds each item of the provided iterable to the TEST_SETTINGS['TEST_INPUT'] list. ## Function: npyscreen.add_test_input_ch(ch) ### Description Adds a single character or key code `ch` to the TEST_SETTINGS['TEST_INPUT'] list. ``` -------------------------------- ### Displaying a Confirmation Message Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Illustrates how to display a confirmation message with OK and Cancel options. ```python npyscreen.notify_confirm('Are you sure you want to proceed?') ``` -------------------------------- ### Creating a Form in npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Demonstrates the basic process of creating a custom Form class in npyscreen by inheriting from npyscreen.Form. ```python class MyForm(npyscreen.Form): def after_creation(self): self.add_widget(npyscreen.TitleText, name='My Text:', value='Default Value') ``` -------------------------------- ### Define Form and Application Source: https://github.com/npcole/npyscreen/blob/master/docs/source/application-structure.md Registers a form named 'MAIN' within the NPSAppManaged application. The application will loop indefinitely on this form. ```default import npyscreen class myEmployeeForm(npyscreen.Form): def create(self): self.myName = self.add(npyscreen.TitleText, name='Name') self.myDepartment = self.add(npyscreen.TitleSelectOne, scroll_exit=True, max_height=3, name='Department', values = ['Department 1', 'Department 2', 'Department 3']) self.myDate = self.add(npyscreen.TitleDateCombo, name='Date Employed') class MyApplication(npyscreen.NPSAppManaged): def onStart(self): self.addForm('MAIN', myEmployeeForm, name='New Employee') if __name__ == '__main__': TestApp = MyApplication().run() print "All objects, baby." ``` -------------------------------- ### Widget Methods Source: https://github.com/npcole/npyscreen/blob/master/docs/source/widgets.md Common methods available for all widgets. ```APIDOC ## Widget Methods ### Methods - **display()** Redraws the widget and updates the curses screen. - **update(clear=True)** Redraws the widget without updating the curses screen. Accepts an optional `clear` argument (boolean) to control whether the widget area is cleared before redrawing. - **when_parent_changes_value()** Called when the parent form's `set_value()` method is invoked. - **when_value_edited()** Called when the widget's value changes during editing. Can be disabled by setting `check_value_change` to False. Can be overridden. - **when_cursor_moved()** Called when the cursor moves within the widget during editing. Can be disabled by setting `check_cursor_move` to False. Can be overridden. - **edit()** Allows the user to interact with and edit the widget. Returns when the user leaves the widget. Generally considered part of the internal API. - **set_relyx()** Sets the position of the widget on the Form. Negative values position relative to the bottom or right edge. Ignores Form margins. (Introduced in Version 4.3.0). ``` -------------------------------- ### SelectOne and TitleSelectOne Widgets Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/widgets-multiline.txt Similar to MultiLine widgets but with a display similar to MultiSelect, allowing only a single selection. ```APIDOC ## SelectOne and TitleSelectOne Widgets ### Description Functionally similar to MultiLine widgets but display options like MultiSelect, enforcing a single selection. `TitleSelectOne` includes a title. ``` -------------------------------- ### Initialize NPSAppManaged Application Source: https://github.com/npcole/npyscreen/blob/master/docs/source/application-structure.md Basic structure for an application using NPSAppManaged. Requires a 'MAIN' form to be defined to avoid exceptions. ```default import npyscreen class MyApplication(npyscreen.NPSAppManaged): pass if __name__ == '__main__': TestApp = MyApplication().run() print "All objects, baby." ``` -------------------------------- ### Implement an OptionList Application in npyscreen Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/options.html Defines a TestApp class that initializes an OptionList with various option types and displays them in a form. ```python # encoding: utf-8 import npyscreen class TestApp(npyscreen.NPSApp): def main(self): Options = npyscreen.OptionList() # just for convenience so we don't have to keep writing Options.options options = Options.options options.append(npyscreen.OptionFreeText('FreeText', value='', documentation="This is some documentation.")) options.append(npyscreen.OptionMultiChoice('Multichoice', choices=['Choice 1', 'Choice 2', 'Choice 3'])) options.append(npyscreen.OptionFilename('Filename', )) options.append(npyscreen.OptionDate('Date', )) options.append(npyscreen.OptionMultiFreeText('Multiline Text', value='')) options.append(npyscreen.OptionMultiFreeList('Multiline List')) try: Options.reload_from_file('/tmp/test') except FileNotFoundError: pass F = npyscreen.Form(name = "Welcome to Npyscreen",) ms = F.add(npyscreen.OptionListDisplay, name="Option List", values = options, scroll_exit=True, max_height=None) F.edit() Options.write_to_file('/tmp/test') if __name__ == "__main__": App = TestApp() App.run() ``` -------------------------------- ### ComboBox and TitleCombo Source: https://github.com/npcole/npyscreen/blob/master/docs/source/widgets-general.md Widgets for selecting from a predefined list of options. ```APIDOC ## ComboBox / TitleCombo ### Description Displays a list of options in a temporary window for selection. ### Attributes - **value** (int) - The index of the current selection in the values list. - **values** (list) - The list of available options. ### Methods - **display_value(self, vl)** - Overload this method to customize how values are displayed. ``` -------------------------------- ### Configure FilenameCombo Constructor Arguments Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/_sources/widgets-general.txt Constructor arguments for FilenameCombo that also serve as persistent widget attributes. ```python select_dir=False must_exist=False confirm_if_exists=False sort_by_extension=True ``` -------------------------------- ### Form Class Overview Source: https://github.com/npcole/npyscreen/blob/master/docs/source/form-objects.md Details on the Form class constructor and its attributes. ```APIDOC ## Form Class ### Description A Form object is a screen area that contains widgets. Forms control which widget a user is editing, and may provide additional functionality, such as pop-up menus or actions that happen on particular keypresses. ### Class Attributes - **DEFAULT_LINES** (int) - Default number of lines for a form. - **DEFAULT_COLUMNS** (int) - Default number of columns for a form. - **SHOW_ATX** (int) - Default X position to show the form. - **SHOW_ATY** (int) - Default Y position to show the form. ### Constructor #### Form(name=None, lines=0, columns=0, minimum_lines=24, minimum_columns=80) **Parameters:** - **name** (str) - Optional name for the Form, often displayed as a title. - **lines** (int) - Absolute number of lines for the Form. Defaults to 0. - **columns** (int) - Absolute number of columns for the Form. Defaults to 0. - **minimum_lines** (int) - Minimum number of lines required for the Form. Defaults to 24. - **minimum_columns** (int) - Minimum number of columns required for the Form. Defaults to 80. **Description:** Initializes a Form object. The constructor calls the `.create()` method, which should be overridden to define the Form's widgets. ``` -------------------------------- ### Add Form Instance - NPSAppManaged Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-objects.html Creates and registers a new form instance with the NPSAppManaged application. Additional arguments are passed to the Form's constructor. Returns a weakref.proxy to the form. ```python Application.addForm(id, FormClass, *args, **keywords) ``` -------------------------------- ### Running an NPSAppManaged Application Source: https://github.com/npcole/npyscreen/blob/master/docs/source/index.md Illustrates how to run an application managed by NPSAppManaged, which handles form transitions and application lifecycle. ```python class MyApp(npyscreen.NPSAppManaged): def onStart(self): self.addForm("MAIN", MyForm, name="My Application") if __name__ == '__main__': app = MyApp() app.run() ``` -------------------------------- ### Switch to Previous Form Immediately - NPSAppManaged Source: https://github.com/npcole/npyscreen/blob/master/docs/build/html/application-objects.html Immediately navigates to the previous form in the history stack. This provides an instant way to go back without triggering exit logic. ```python Application.switchFormPrevious() ```