Initial commit

This commit is contained in:
2023-08-23 11:11:51 -04:00
commit 32bdc6a287
16 changed files with 694 additions and 0 deletions

59
readline/creatures.py Normal file
View File

@ -0,0 +1,59 @@
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)]
if state < len(options):
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: ")
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.")

29
readline/mtg.py Normal file
View File

@ -0,0 +1,29 @@
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)'
]
class mycmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
def do_quit(self, s):
return True
def do_add(self, s):
pass
def complete_add(self, text, line, begidx, endidx):
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in completions if s.startswith(mline)]
if __name__ == '__main__':
mycmd().cmdloop()

View File

@ -0,0 +1,92 @@
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)

54
readline/readline_calc.py Normal file
View File

@ -0,0 +1,54 @@
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)

66
readline/readline_cmd.py Normal file
View File

@ -0,0 +1,66 @@
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)

39
readline/readline_test.py Normal file
View File

@ -0,0 +1,39 @@
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)