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

求将systemctl -h输出解析为Python3字典列表的实现方案

Parse systemctl -h Output into Python Dictionary List

Here's a concise Python solution that meets your requirements—fetching systemctl -h output, parsing sections, and structuring options into a list of dictionaries with the fields you specified.

Full Code

import subprocess
import json

def get_systemctl_help_lines():
    """Fetch and split systemctl help output into lines."""
    result = subprocess.run(
        ['systemctl', '-h'],
        capture_output=True,
        text=True,
        check=True
    )
    return result.stdout.splitlines()

def parse_systemctl_help(lines):
    """Parse help lines into the desired structure."""
    help_output = []
    current_section = None
    current_option = None

    for line in lines:
        stripped_line = line.strip()
        
        # Skip empty lines
        if not stripped_line:
            continue
        
        # Detect section headers (lines ending with colon)
        if stripped_line.endswith(':'):
            # Finalize the previous section if exists
            if current_section:
                help_output.append(current_section)
            # Initialize new section
            section_name = stripped_line[:-1].strip()
            current_section = {
                'section': section_name,
                'options': []
            }
            current_option = None
            continue
        
        # Process option lines within the current section
        if current_section:
            # Handle wrapped descriptions (indented continuation lines)
            if current_option and line.startswith((' ', '\t')):
                current_option['description'] += f" {stripped_line}"
                continue
            
            # Split option part from description
            parts = stripped_line.split(maxsplit=1)
            if len(parts) == 1:
                longcode = parts[0]
                description = ""
                shortcode = None
            else:
                option_part, description = parts
                description = description.strip()
                
                # Split short and long codes if present (e.g., "-h --help")
                if ' ' in option_part:
                    shortcode, longcode = option_part.split(' ', 1)
                else:
                    # Determine if it's a short code, long code, or command
                    if option_part.startswith('--'):
                        longcode = option_part
                        shortcode = None
                    elif option_part.startswith('-'):
                        shortcode = option_part
                        longcode = None
                    else:
                        longcode = option_part
                        shortcode = None
            
            # Create and add new option
            current_option = {
                'shortcode': shortcode,
                'longcode': longcode,
                'description': description
            }
            current_section['options'].append(current_option)
    
    # Add the last section to the output
    if current_section:
        help_output.append(current_section)
    
    return help_output

if __name__ == '__main__':
    help_lines = get_systemctl_help_lines()
    parsed_help = parse_systemctl_help(help_lines)
    # Print formatted output for verification
    print(json.dumps(parsed_help, indent=2))

Key Features

  • Section Detection: Identifies section headers (like "General Commands:" or "Options:") by checking for lines ending with a colon.
  • Option Parsing:
    • Handles both short/long option pairs (e.g., -h --help) and standalone commands/long options (e.g., list-units, --version).
    • Captures command syntax including arguments (e.g., start UNIT...).
  • Wrapped Description Handling: Merges multi-line descriptions that are indented under an option.
  • Clean Structure: Outputs a list of dictionaries where each entry represents a section, containing a list of its options with shortcode, longcode, and description.

Example Output Snippet

[
  {
    "section": "General Commands",
    "options": [
      {
        "shortcode": null,
        "longcode": "help",
        "description": "Show this help message"
      },
      {
        "shortcode": null,
        "longcode": "list-units [PATTERN...]",
        "description": "List loaded units"
      }
    ]
  },
  {
    "section": "Options",
    "options": [
      {
        "shortcode": "-h",
        "longcode": "--help",
        "description": "Show this help message"
      },
      {
        "shortcode": null,
        "longcode": "--version",
        "description": "Show package version"
      }
    ]
  }
]

Content of the question originates from Stack Exchange, asked by daxmick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:44:09