function run_command
Executes a shell command with error handling and provides formatted console output with status indicators (emoji-based feedback).
/tf/active/vicechatdev/email-forwarder/setup_venv.py
13 - 25
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.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function main_v41 43.7% similar
-
function run_server 43.0% similar
-
function main_v50 42.8% similar
-
function main_v67 41.9% similar
-
function main_v32 41.6% similar