Update examples
This commit is contained in:
		
							
								
								
									
										58
									
								
								readline/creatures.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							
							
						
						
									
										58
									
								
								readline/creatures.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							| @@ -1,12 +1,21 @@ | ||||
| #!/usr/bin/env | ||||
| """ | ||||
| This module implements a simple console application to manage a list of creatures. | ||||
| It provides functionalities to add a creature to the list, lookup creatures with  | ||||
| autocomplete support (press tab to auto-complete creature names), and quit the  | ||||
| application. | ||||
| """ | ||||
| import readline | ||||
|  | ||||
| creatures = [] | ||||
|  | ||||
|  | ||||
| def add_creature(): | ||||
|     creature = input("Enter a creature name: ") | ||||
|     creatures.append(creature) | ||||
|     print(f"{creature} added to the list of creatures.") | ||||
|  | ||||
|  | ||||
| def lookup_creature(): | ||||
|     def completer(text, state): | ||||
|         options = [c for c in creatures if c.startswith(text)] | ||||
| @@ -14,46 +23,51 @@ def lookup_creature(): | ||||
|             return options[state] | ||||
|         else: | ||||
|             return None | ||||
|      | ||||
|  | ||||
|     readline.set_completer(completer) | ||||
|     readline.parse_and_bind("tab: complete") | ||||
|      | ||||
|  | ||||
|     print("List of creatures:") | ||||
|     for creature in creatures: | ||||
|         print(f"- {creature}") | ||||
|      | ||||
|  | ||||
|     while True: | ||||
|         creature = input("Enter the name of a creature or press enter to return to the main menu: ") | ||||
|         creature = input( | ||||
|             "Enter the name of a creature or press enter to return to the main menu: " | ||||
|         ) | ||||
|         if not creature: | ||||
|             break | ||||
|         elif creature in creatures: | ||||
|             print(f"{creature} found!") | ||||
|         else: | ||||
|             print(f"{creature} not found.") | ||||
|      | ||||
|  | ||||
|     readline.set_completer(None) | ||||
|     readline.parse_and_bind("tab: ") | ||||
|  | ||||
|  | ||||
| def quit(): | ||||
|     print("Goodbye!") | ||||
|     exit() | ||||
|  | ||||
| menu = { | ||||
|     "1": add_creature, | ||||
|     "2": lookup_creature, | ||||
|     "3": quit | ||||
| } | ||||
|  | ||||
| while True: | ||||
|     print("Menu:") | ||||
|     print("[1] Add Creature") | ||||
|     print("[2] Lookup Creature") | ||||
|     print("[3] Quit") | ||||
|      | ||||
|     choice = input("Enter your choice: ") | ||||
|     action = menu.get(choice) | ||||
|     if action: | ||||
|         action() | ||||
|     else: | ||||
|         print(f"{choice} is not a valid option.") | ||||
| menu = {"1": add_creature, "2": lookup_creature, "3": quit} | ||||
|  | ||||
|  | ||||
| def main(): | ||||
|     while True: | ||||
|         print("Menu:") | ||||
|         print("[1] Add Creature") | ||||
|         print("[2] Lookup Creature") | ||||
|         print("[3] Quit") | ||||
|  | ||||
|         choice = input("Enter your choice: ") | ||||
|         action = menu.get(choice) | ||||
|         if action: | ||||
|             action() | ||||
|         else: | ||||
|             print(f"{choice} is not a valid option.") | ||||
|  | ||||
|  | ||||
| if __name__ == "__main__": | ||||
|     main() | ||||
|   | ||||
							
								
								
									
										29
									
								
								readline/mtg.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							
							
						
						
									
										29
									
								
								readline/mtg.py
									
									
									
									
									
										
										
										Normal file → Executable file
									
								
							| @@ -1,15 +1,25 @@ | ||||
| #!/usr/bin/env python3 | ||||
| """ | ||||
| This module defines a command-line interface (CLI) application which allows | ||||
| users to interact with a predefined list of completion options, specifically, | ||||
| card names from the "Alara Reborn" set. | ||||
|  | ||||
| It leverages the `cmd` module to build the CLI and has tab-completion  | ||||
| functionality for adding items from the predefined list of card names. | ||||
| """ | ||||
| import cmd | ||||
|  | ||||
| completions = [ | ||||
|     'Mage Slayer (Alara Reborn)', | ||||
|     'Magefire Wings (Alara Reborn)', | ||||
|     'Sages of the Anima (Alara Reborn)', | ||||
|     'Sanctum Plowbeast (Alara Reborn)', | ||||
|     'Sangrite Backlash (Alara Reborn)', | ||||
|     'Sanity Gnawers (Alara Reborn)', | ||||
|     'Sen Triplets (Alara Reborn)' | ||||
|     "Mage Slayer (Alara Reborn)", | ||||
|     "Magefire Wings (Alara Reborn)", | ||||
|     "Sages of the Anima (Alara Reborn)", | ||||
|     "Sanctum Plowbeast (Alara Reborn)", | ||||
|     "Sangrite Backlash (Alara Reborn)", | ||||
|     "Sanity Gnawers (Alara Reborn)", | ||||
|     "Sen Triplets (Alara Reborn)", | ||||
| ] | ||||
|  | ||||
|  | ||||
| class mycmd(cmd.Cmd): | ||||
|     def __init__(self): | ||||
|         cmd.Cmd.__init__(self) | ||||
| @@ -21,9 +31,10 @@ class mycmd(cmd.Cmd): | ||||
|         pass | ||||
|  | ||||
|     def complete_add(self, text, line, begidx, endidx): | ||||
|         mline = line.partition(' ')[2] | ||||
|         mline = line.partition(" ")[2] | ||||
|         offs = len(mline) - len(text) | ||||
|         return [s[offs:] for s in completions if s.startswith(mline)] | ||||
|  | ||||
| if __name__ == '__main__': | ||||
|  | ||||
| if __name__ == "__main__": | ||||
|     mycmd().cmdloop() | ||||
|   | ||||
| @@ -1,92 +0,0 @@ | ||||
| import cmd | ||||
| import os | ||||
| import readline | ||||
| import sys | ||||
|  | ||||
| # Set up history file | ||||
| histfile = os.path.join(os.path.expanduser('~'), '.history') | ||||
| try: | ||||
|     readline.read_history_file(histfile) | ||||
| except FileNotFoundError: | ||||
|     open(histfile, 'wb').close() | ||||
|  | ||||
| # Define add and subtract functions | ||||
| def add(x, y): | ||||
|     return x + y | ||||
|  | ||||
| def subtract(x, y): | ||||
|     return x - y | ||||
|  | ||||
| # Define command processor | ||||
| class MyCmd(cmd.Cmd): | ||||
|     prompt = '> ' | ||||
|     intro = 'Type help for commands' | ||||
|  | ||||
|     def do_exit(self, arg): | ||||
|         """Exit the program""" | ||||
|         return True | ||||
|  | ||||
|     def do_add(self, arg): | ||||
|         """Add two numbers: add <num1> <num2>""" | ||||
|         try: | ||||
|             num1, num2 = map(float, arg.split()) | ||||
|         except ValueError: | ||||
|             print('Invalid input') | ||||
|             return | ||||
|         print(add(num1, num2)) | ||||
|  | ||||
|     def complete_add(self, text, line, begidx, endidx): | ||||
|         if not text: | ||||
|             completions = ['<num1>', '<num2>'] | ||||
|         elif '<num1>' in line: | ||||
|             completions = ['<num2>'] | ||||
|         else: | ||||
|             completions = ['<num1>'] | ||||
|         return [c for c in completions if c.startswith(text)] | ||||
|  | ||||
|     def do_subtract(self, arg): | ||||
|         """Subtract two numbers: subtract <num1> <num2>""" | ||||
|         try: | ||||
|             num1, num2 = map(float, arg.split()) | ||||
|         except ValueError: | ||||
|             print('Invalid input') | ||||
|             return | ||||
|         print(subtract(num1, num2)) | ||||
|  | ||||
|     def complete_subtract(self, text, line, begidx, endidx): | ||||
|         if not text: | ||||
|             completions = ['<num1>', '<num2>'] | ||||
|         elif '<num1>' in line: | ||||
|             completions = ['<num2>'] | ||||
|         else: | ||||
|             completions = ['<num1>'] | ||||
|         return [c for c in completions if c.startswith(text)] | ||||
|  | ||||
|     def do_clear(self, arg): | ||||
|         """Clear the screen""" | ||||
|         if sys.platform.startswith('win'): | ||||
|             os.system('cls') | ||||
|         else: | ||||
|             os.system('clear') | ||||
|  | ||||
|     def default(self, line): | ||||
|         print('Invalid command') | ||||
|  | ||||
|     def emptyline(self): | ||||
|         pass | ||||
|  | ||||
| # Run command processor | ||||
| console = MyCmd() | ||||
| readline.set_completer_delims(' \t\n;') | ||||
| readline.parse_and_bind('tab: complete') | ||||
| while True: | ||||
|     try: | ||||
|         line = input(console.prompt) | ||||
|     except EOFError: | ||||
|         break | ||||
|     console.onecmd(line) | ||||
|  | ||||
| # Save history file | ||||
| with open(histfile, 'w') as f: | ||||
|     readline.write_history_file(histfile) | ||||
|  | ||||
| @@ -1,54 +0,0 @@ | ||||
| import readline | ||||
|  | ||||
| # Set up history file | ||||
| histfile = '.history' | ||||
| try: | ||||
|     readline.read_history_file(histfile) | ||||
| except FileNotFoundError: | ||||
|     open(histfile, 'wb').close() | ||||
|  | ||||
| # Define add and subtract functions | ||||
| def add(x, y): | ||||
|     return x + y | ||||
|  | ||||
| def subtract(x, y): | ||||
|     return x - y | ||||
|  | ||||
| # Loop for user input | ||||
| while True: | ||||
|     # Read user input | ||||
|     try: | ||||
|         line = input('> ') | ||||
|     except EOFError: | ||||
|         break | ||||
|  | ||||
|     # Check for exit command | ||||
|     if line == 'exit': | ||||
|         break | ||||
|  | ||||
|     # Parse user input | ||||
|     try: | ||||
|         args = line.split() | ||||
|         if len(args) != 3: | ||||
|             raise ValueError | ||||
|         num1 = float(args[0]) | ||||
|         num2 = float(args[2]) | ||||
|         op = args[1] | ||||
|         if op not in ['+', '-']: | ||||
|             raise ValueError | ||||
|     except ValueError: | ||||
|         print('Invalid input') | ||||
|         continue | ||||
|  | ||||
|     # Perform operation | ||||
|     if op == '+': | ||||
|         result = add(num1, num2) | ||||
|     else: | ||||
|         result = subtract(num1, num2) | ||||
|  | ||||
|     # Print result and add command to history | ||||
|     print(result) | ||||
|     readline.add_history(line) | ||||
|  | ||||
| # Save history file | ||||
| readline.write_history_file(histfile) | ||||
| @@ -1,66 +0,0 @@ | ||||
| import cmd | ||||
| import os | ||||
| import readline | ||||
|  | ||||
| # Set up history file | ||||
| histfile = os.path.join(os.path.expanduser('~'), '.history') | ||||
| try: | ||||
|     readline.read_history_file(histfile) | ||||
| except FileNotFoundError: | ||||
|     open(histfile, 'wb').close() | ||||
|  | ||||
| # Define add and subtract functions | ||||
| def add(x, y): | ||||
|     return x + y | ||||
|  | ||||
| def subtract(x, y): | ||||
|     return x - y | ||||
|  | ||||
| # Define command processor | ||||
| class MyCmd(cmd.Cmd): | ||||
|     prompt = '> ' | ||||
|     intro = 'Type help for commands' | ||||
|  | ||||
|     def do_exit(self, arg): | ||||
|         """Exit the program""" | ||||
|         return True | ||||
|  | ||||
|     def do_add(self, arg): | ||||
|         """Add two numbers: add <num1> <num2>""" | ||||
|         try: | ||||
|             num1, num2 = map(float, arg.split()) | ||||
|         except ValueError: | ||||
|             print('Invalid input') | ||||
|             return | ||||
|         print(add(num1, num2)) | ||||
|  | ||||
|     def do_subtract(self, arg): | ||||
|         """Subtract two numbers: subtract <num1> <num2>""" | ||||
|         try: | ||||
|             num1, num2 = map(float, arg.split()) | ||||
|         except ValueError: | ||||
|             print('Invalid input') | ||||
|             return | ||||
|         print(subtract(num1, num2)) | ||||
|  | ||||
|     def default(self, line): | ||||
|         print('Invalid command') | ||||
|  | ||||
|     def emptyline(self): | ||||
|         pass | ||||
|  | ||||
| # Run command processor | ||||
| console = MyCmd() | ||||
| readline.set_completer_delims(' \t\n;') | ||||
| readline.parse_and_bind('tab: complete') | ||||
| while True: | ||||
|     try: | ||||
|         line = input(console.prompt) | ||||
|     except EOFError: | ||||
|         break | ||||
|     console.onecmd(line) | ||||
|  | ||||
| # Save history file | ||||
| with open(histfile, 'w') as f: | ||||
|     readline.write_history_file(histfile) | ||||
|  | ||||
| @@ -1,39 +0,0 @@ | ||||
| import atexit | ||||
| import code | ||||
| import os | ||||
| import readline | ||||
|  | ||||
| class HistoryConsole(code.InteractiveConsole): | ||||
|     def __init__(self, locals=None, filename="<console>", | ||||
|                  histfile=os.path.expanduser("~/.console-history")): | ||||
|         code.InteractiveConsole.__init__(self, locals, filename) | ||||
|         self.init_history(histfile) | ||||
|  | ||||
|     def init_history(self, histfile): | ||||
|         readline.parse_and_bind("tab: complete") | ||||
|         if hasattr(readline, "read_history_file"): | ||||
|             try: | ||||
|                 readline.read_history_file(histfile) | ||||
|             except FileNotFoundError: | ||||
|                 pass | ||||
|             atexit.register(self.save_history, histfile) | ||||
|  | ||||
|     def save_history(self, histfile): | ||||
|         readline.set_history_length(1000) | ||||
|         readline.write_history_file(histfile) | ||||
|  | ||||
|  | ||||
| # Run console | ||||
| console = HistoryConsole() | ||||
| while True: | ||||
|     try: | ||||
|         line = input('> ') | ||||
|     except EOFError: | ||||
|         break | ||||
|  | ||||
|     # Check for exit command | ||||
|     if line == 'exit': | ||||
|         break | ||||
|  | ||||
|     # Process user input | ||||
|     console.push(line) | ||||
		Reference in New Issue
	
	Block a user