can you write python code for a generic "cli menu" running under windows? it reads lines from a text file and then displays the multiple options.
Each option has a name to diplay and a matching shell command. Both are read from the text file. You can use the arrow up and arrow down keys to navigate the menu.The cursor is simply represented as a '*' in front of the current entry. When you press enter the corresponding shell command is executed.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, here is an example of a generic CLI menu in Python that reads lines from a text file and displays multiple options, allowing the user to navigate the menu using the arrow up and arrow down keys, and execute the corresponding shell command when pressing enter:
code
import sys
# Load the menu items from the text file
with open("menu.txt", "r") as f:
menu_items = f.readlines()
# Split each menu item into its name and command
menu_items = [item.split(":") for item in menu_items]
# Display the menu items
def display_menu():
for i, item in enumerate(menu_items):
print(f"{i+1}. {item[0]}")
# Read user input and execute the corresponding command
def read_input():
input_ = input("Enter a number or press Enter to execute: ")
if input_.isdigit():
num = int(input_) - 1
if num >= 0 and num < len(menu_items):
command = menu_items[num][1]
print(f"Executing command: {command}")
os.system(command)
else:
print("Invalid input")
else:
print("Invalid input")
# Main loop
while True:
display_menu()
read_input()
This code assumes that the menu items are stored in a file called "menu.txt", with each line in the file containing the name of the option followed by a colon and the corresponding shell command. For example:
The code first loads the menu items from the text file and splits each line into its name and command using the split() method. It then defines a function called display_menu() that prints out each menu item, along with its number, on a separate line.
The read_input() function reads user input and tries to execute the corresponding command. If the user enters a number, the function uses the int() function to convert the input to an integer and then uses the os.system() function to execute the corresponding command. If the user enters anything else, the function prints an error message.