如何将os.popen输出转为动态选择菜单作为其他程序输入?
Got it, let's tackle this problem of turning os.popen output into a dynamic terminal menu—perfect for when you can't predict how many options you'll end up with. Here's a straightforward, practical approach with code examples you can adapt right away.
First, your current code grabs the full command output as a single string. We need to split that into individual, clean options. Assuming your dzdo command outputs one item per line (like tiger, lion, elephant each on their own line), we can split by newlines and filter out empty lines or noise:
import os # Replace these with your actual sid and target values sid = "your_sid_value" target_view = "your_target_view" # Build the command string SG = f"dzdo symaccess -sid {sid} show {target_view} view -detail" # Execute the command and read output raw_output = os.popen(SG).read() # Split into lines, strip whitespace, and filter out empty lines menu_options = [line.strip() for line in raw_output.split('\n') if line.strip()] # Now menu_options is your dynamic list of choices print(menu_options) # Example output: ['tiger', 'lion', 'elephant']
For a lightweight, easy-to-use terminal menu, simple-term-menu is a great choice—it handles dynamic option counts seamlessly. First install it:
pip install simple-term-menu
Then integrate it into your code:
from simple_term_menu import TerminalMenu import os sid = "your_sid_value" target_view = "your_target_view" SG = f"dzdo symaccess -sid {sid} show {target_view} view -detail" raw_output = os.popen(SG).read() menu_options = [line.strip() for line in raw_output.split('\n') if line.strip()] if not menu_options: print("No valid options found from the command output.") else: # Initialize the menu with your dynamic options menu = TerminalMenu(menu_options) selected_index = menu.show() # Shows the menu and returns the selected index selected_option = menu_options[selected_index] print(f"You selected: {selected_option}") # Pass selected_option to your other program here (e.g., via subprocess, stdin, etc.)
inquirer for More Polished Interactions If you want a menu with nicer formatting (like arrow key navigation and visual highlights), try the inquirer library. Install it first:
pip install inquirer
Here's how to use it:
import inquirer import os sid = "your_sid_value" target_view = "your_target_view" SG = f"dzdo symaccess -sid {sid} show {target_view} view -detail" raw_output = os.popen(SG).read() menu_options = [line.strip() for line in raw_output.split('\n') if line.strip()] if not menu_options: print("No options available.") else: # Define the menu question questions = [ inquirer.List( 'selected_item', message="Choose an option:", choices=menu_options, ) ] # Show the menu and get the selection answers = inquirer.prompt(questions) selected_option = answers['selected_item'] print(f"You selected: {selected_option}") # Use selected_option as input for your other program
- Clean Up Output: If your
dzdocommand outputs headers or extra lines (like separators), add filters tomenu_optionsto exclude them. For example:menu_options = [ line.strip() for line in raw_output.split('\n') if line.strip() and not line.startswith('---') # Skip separator lines and not line.startswith('SID:') # Skip header lines ] - Prefer
subprocessOveros.popen: For better security and error handling, replaceos.popenwithsubprocess.check_output:import subprocess try: raw_output = subprocess.check_output(SG, shell=True, text=True) except subprocess.CalledProcessError as e: print(f"Command failed with error: {e}") menu_options = []
内容的提问来源于stack exchange,提问作者kalyanyellapu

