🔍 Code Extractor

function run_command

Maturity: 44

Executes a shell command with error handling and provides formatted console output with status indicators (emoji-based feedback).

File:
/tf/active/vicechatdev/email-forwarder/setup_venv.py
Lines:
13 - 25
Complexity:
simple

Purpose

This function serves as a wrapper for executing shell commands via subprocess, providing user-friendly console feedback with emoji indicators for progress, success, and failure states. It captures both stdout and stderr, displays relevant output, and returns a boolean indicating command success. Useful for automation scripts, deployment pipelines, or any scenario requiring shell command execution with clear visual feedback.

Source Code

def run_command(cmd, description):
    """Run a shell command and handle errors."""
    print(f"🔄 {description}...")
    try:
        result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
        print(f"✅ {description} - Success")
        if result.stdout.strip():
            print(f"   Output: {result.stdout.strip()}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} - Failed")
        print(f"   Error: {e.stderr.strip() if e.stderr else str(e)}")
        return False

Parameters

Name Type Default Kind
cmd - - positional_or_keyword
description - - positional_or_keyword

Parameter Details

cmd: String containing the shell command to execute. Can be a simple command or a complex shell expression with pipes, redirects, etc. Executed through shell=True, so shell syntax is supported.

description: String describing the operation being performed. Used in console output to inform users what action is being taken. Should be a brief, human-readable description (e.g., 'Installing dependencies', 'Building Docker image').

Return Value

Returns a boolean value: True if the command executed successfully (exit code 0), False if the command failed (non-zero exit code or exception occurred). This allows callers to implement conditional logic based on command success.

Dependencies

  • subprocess

Required Imports

import subprocess

Usage Example

import subprocess

def run_command(cmd, description):
    """Run a shell command and handle errors."""
    print(f"🔄 {description}...")
    try:
        result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
        print(f"✅ {description} - Success")
        if result.stdout.strip():
            print(f"   Output: {result.stdout.strip()}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} - Failed")
        print(f"   Error: {e.stderr.strip() if e.stderr else str(e)}")
        return False

# Example usage
success = run_command('ls -la', 'Listing directory contents')
if success:
    print('Command completed successfully')
else:
    print('Command failed')

# Example with git command
run_command('git status', 'Checking git status')

# Example with conditional execution
if run_command('npm install', 'Installing npm packages'):
    run_command('npm run build', 'Building project')

Best Practices

  • Be cautious with shell=True as it can pose security risks if cmd contains untrusted input. Consider using shell=False with a list of arguments for better security.
  • The function captures all output (capture_output=True), which may cause issues with very large outputs that could consume significant memory.
  • Commands are executed synchronously and will block until completion. For long-running commands, consider adding timeout parameters or async alternatives.
  • The function prints directly to console, which may not be suitable for all contexts (e.g., libraries, background services). Consider adding a logging parameter or using proper logging instead of print statements.
  • Return value is boolean only - consider capturing and returning the actual output or result object if callers need access to stdout/stderr.
  • Error messages only show stderr when available; some commands may write errors to stdout instead.
  • The text=True parameter ensures output is decoded as strings; ensure your environment's default encoding is appropriate for the commands being run.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v41 43.7% similar

    Entry point function that parses command-line arguments and orchestrates the FileCloud email processing workflow to find, download, and convert .msg files.

    From: /tf/active/vicechatdev/msg_to_eml.py
  • function run_server 43.0% similar

    Initializes and runs an asynchronous SMTP server with platform-specific event loop configuration and error handling.

    From: /tf/active/vicechatdev/email-forwarder/src/main.py
  • function main_v50 42.8% similar

    A command-line interface (CLI) entry point that parses command-line arguments and dispatches to various development tool functions for managing browser cache, static files, and debug endpoints.

    From: /tf/active/vicechatdev/vice_ai/dev_tools.py
  • function main_v67 41.9% similar

    Command-line interface function that parses arguments and sends a test email through an SMTP forwarder service, displaying connection details and returning an exit code based on success.

    From: /tf/active/vicechatdev/email-forwarder/send_test_email.py
  • function main_v32 41.6% similar

    Command-line interface entry point for monitoring SharePoint to FileCloud synchronization logs, providing status analysis, log tailing, and real-time watching capabilities.

    From: /tf/active/vicechatdev/SPFCsync/monitor.py
← Back to Browse