You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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.

Step 1: Parse the Command Output

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']
Step 2: Create a Dynamic Menu with simple-term-menu

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.)
Alternative: Use 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
Key Notes for Robustness
  • Clean Up Output: If your dzdo command outputs headers or extra lines (like separators), add filters to menu_options to 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 subprocess Over os.popen: For better security and error handling, replace os.popen with subprocess.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:01:04