Wednesday, October 15, 2025

Command Line Interface (CLI)

 CLI Usage in Python: Basics and Best Practices

Command Line Interface (CLI) refers to interacting with programs via a terminal or shell (e.g., Command Prompt on Windows, Terminal on macOS/Linux). In Python, CLI usage is essential for running scripts, managing packages, and building user-friendly tools that accept inputs like flags or arguments without a GUI. It's efficient for automation, scripting, and server-side apps.Python's standard library supports CLI via modules like sys (for basic args) and argparse (for advanced parsing). Third-party libs like click or typer simplify complex CLIs.Why Use CLI?
  • Portability: Runs anywhere with a terminal.
  • Automation: Integrate with scripts, cron jobs, or pipelines.
  • Simplicity: No need for web/GUI frameworks.
Common Python CLI Commands
Command
Description
Example
python script.py
Run a Python script.
python hello.py
python -m module
Run as module (e.g., for tools).
python -m venv myenv
python -c "code"
Execute inline code.
python -c "print('Hi')"
pip install pkg
Install packages (in venv!).
pip install requests
python -m pip freeze > req.txt
Export requirements.
Saves deps to file
Handling CLI Arguments
  1. Basic: Using sys.argv
    Access command-line args as a list (sys.argv[0] is script name).
    python
    import sys
    
    if len(sys.argv) > 1:
        name = sys.argv[1]  # First arg
        print(f"Hello, {name}!")
    else:
        print("Usage: python script.py <name>")
    Run: python script.py Alice → Outputs "Hello, Alice!"
  2. Advanced: Using argparse
    Built-in for flags, options, help text, and validation.
    python
    import argparse
    
    parser = argparse.ArgumentParser(description="Greet someone")
    parser.add_argument("name", help="Person's name")
    parser.add_argument("-g", "--greeting", default="Hello", help="Custom greeting")
    
    args = parser.parse_args()
    print(f"{args.greeting}, {args.name}!")
    Run:
    • python script.py Alice → "Hello, Alice!"
    • python script.py Alice -g Hi → "Hi, Alice!"
    • python script.py -h → Shows help.
Building a Simple CLI ToolCombine with previous topics (e.g., file I/O in a venv):
python
# cli_tool.py - Reads a file and outputs uppercase version
import argparse
import sys

parser = argparse.ArgumentParser(description="Process text files")
parser.add_argument("input_file", help="Input file path")
parser.add_argument("output_file", nargs="?", default=None, help="Output file (optional)")
parser.add_argument("-u", "--upper", action="store_true", help="Convert to uppercase")

args = parser.parse_args()

try:
    with open(args.input_file, 'r') as infile:
        data = infile.read()
    if args.upper:
        data = data.upper()
    
    if args.output_file:
        with open(args.output_file, 'w') as outfile:
            outfile.write(data)
        print(f"Written to {args.output_file}")
    else:
        print(data)  # Output to console
except FileNotFoundError:
    print(f"Error: {args.input_file} not found", file=sys.stderr)
Run in activated venv: python cli_tool.py input.txt -u (uppercases and prints).Tips
  • Error Handling: Use sys.exit(1) for failures; check argparse for auto-help.
  • Shebang: Add #!/usr/bin/env python at script top for direct execution (chmod +x script.py; ./script.py).
  • Testing: Use python -m unittest for CLI tests.
  • Advanced: Try click for decorators: pip install click, then @click.command().
If you mean CLI for a specific tool (e.g., pip, git) or want examples in another language, clarify! Ready for hands-on? Share a script idea.

Lecture Notes: Optimising Numerical Code

Lecture Notes: Optimising Numerical Code Prerequisites: Basic Python programming Understanding of NumPy arrays and vector ...