Command Line

Back

Loading concept...

🎒 The Mailman’s Secret Toolkit

How Python Talks to the Outside World


Imagine you’re a mailman named Python. Every day, you deliver packages (run programs). But here’s the thing—sometimes people shout instructions at you from their doorsteps:

“Hey Python! Deliver this to room 5!” “Python! Use the express route today!”

These shouted instructions? That’s what command line arguments are. And today, you’re going to learn how to listen to them!


📦 Chapter 1: sys.argv — The Mailman’s Ear

The Simple Truth

When someone runs your Python program from the terminal, they can add extra words. Python collects these words into a list called sys.argv.

import sys
print(sys.argv)

If someone runs:

python mailman.py room5 express

Python hears:

['mailman.py', 'room5', 'express']

🧠 Breaking It Down

Position What It Is Example
sys.argv[0] The script name 'mailman.py'
sys.argv[1] First argument 'room5'
sys.argv[2] Second argument 'express'

📝 Real Example

import sys

if len(sys.argv) < 2:
    print("Tell me your name!")
else:
    name = sys.argv[1]
    print(f"Hello, {name}!")

Run it:

python greet.py Alex

Output:

Hello, Alex!

⚡ Quick Tip

Always check len(sys.argv) before accessing arguments. Otherwise, Python will crash like a mailman tripping over an empty mailbox!


🔧 Chapter 2: argparse — The Smart Assistant

Why Do We Need This?

Using sys.argv directly is like reading messy handwriting. What if someone types things in the wrong order? What if they forget something?

argparse is your smart assistant who:

  • Understands named options like --name Alex
  • Provides helpful error messages
  • Creates automatic help screens

The Basic Recipe

import argparse

parser = argparse.ArgumentParser(
    description="Greet someone nicely"
)
parser.add_argument("name", help="Person's name")
args = parser.parse_args()

print(f"Hello, {args.name}!")

Run it:

python greet.py Alex

🎁 The Magic: Free Help Screen

python greet.py --help

Output:

usage: greet.py [-h] name

Greet someone nicely

positional arguments:
  name        Person's name

optional arguments:
  -h, --help  show this message

Adding Optional Arguments

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument(
    "--shout",
    action="store_true",
    help="Shout the greeting"
)
args = parser.parse_args()

greeting = f"Hello, {args.name}!"
if args.shout:
    greeting = greeting.upper()
print(greeting)
python greet.py Alex --shout

Output:

HELLO, ALEX!

🎯 Chapter 3: Argument Types and Choices

The Problem

By default, arguments come in as strings. But what if you need a number?

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "age",
    type=int,
    help="Your age"
)
args = parser.parse_args()

print(f"In 10 years, you'll be {args.age + 10}")

Common Types

Type What It Does Example
str Text (default) "hello"
int Whole numbers 42
float Decimal numbers 3.14

Limiting Choices

Sometimes you only want specific options. Like a restaurant menu!

import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    "size",
    choices=["small", "medium", "large"],
    help="Pick your pizza size"
)
args = parser.parse_args()

print(f"One {args.size} pizza coming up!")
python pizza.py medium

If someone tries python pizza.py huge:

error: argument size: invalid choice:
'huge' (choose from 'small', 'medium', 'large')

🎨 Visual Flow

graph TD A["User Types Command"] --> B["argparse Reads It"] B --> C{Valid Type?} C -->|Yes| D{Valid Choice?} C -->|No| E["Type Error"] D -->|Yes| F["Success!"] D -->|No| G["Choice Error"]

🌍 Chapter 4: Environment Variables

A Different Kind of Message

Imagine if instead of shouting at the mailman, you put a sticky note on your door that says “Always use the back entrance.”

That’s an environment variable—a setting that your computer remembers and shares with every program.

Reading Environment Variables

import os

home = os.environ.get("HOME")
print(f"Your home folder is: {home}")

Common Environment Variables

Variable What It Is Example
HOME Home directory /home/alex
PATH Where programs live /usr/bin
USER Current username alex

Setting Your Own

import os

# Set a variable
os.environ["MY_SECRET"] = "pizza123"

# Read it back
secret = os.environ.get("MY_SECRET")
print(f"The secret is: {secret}")

Using Default Values

What if the sticky note isn’t there? Use a fallback!

import os

# Get DATABASE_URL or use default
db_url = os.environ.get(
    "DATABASE_URL",
    "sqlite:///local.db"
)
print(f"Connecting to: {db_url}")

🛠️ Chapter 5: sys Module Basics

Your Python Toolbox

The sys module is like a toolbox full of useful gadgets for talking to your computer.

Essential Tools

1. sys.argv (Already learned!)

The list of command line arguments.

2. sys.exit() — Emergency Stop

import sys

if something_wrong:
    print("Oops! Something broke.")
    sys.exit(1)  # Exit with error

print("All good!")
sys.exit(0)  # Exit successfully
Exit Code Meaning
0 Everything is fine
1 or higher Something went wrong

3. sys.version — Who Am I?

import sys
print(sys.version)

Output:

3.11.0 (main, Oct 24 2022)

4. sys.platform — Where Am I?

import sys
print(sys.platform)
Platform Output
Linux linux
macOS darwin
Windows win32

5. sys.path — Where to Find Modules

import sys
for folder in sys.path:
    print(folder)

This shows all folders where Python looks for modules when you import something.


🎁 Putting It All Together

Here’s a complete example that uses everything:

import sys
import os
import argparse

# Check Python version first
if sys.version_info < (3, 8):
    print("Need Python 3.8+!")
    sys.exit(1)

# Setup argument parser
parser = argparse.ArgumentParser(
    description="Send a message"
)
parser.add_argument(
    "message",
    help="What to say"
)
parser.add_argument(
    "--loud",
    action="store_true",
    help="Shout it"
)
parser.add_argument(
    "--times",
    type=int,
    default=1,
    choices=[1, 2, 3],
    help="How many times"
)

args = parser.parse_args()

# Get username from environment
user = os.environ.get("USER", "friend")

# Build the message
msg = args.message
if args.loud:
    msg = msg.upper()

# Print it
for i in range(args.times):
    print(f"{user} says: {msg}")

sys.exit(0)

Run it:

python speak.py "Hello World" --loud --times 2

Output:

alex says: HELLO WORLD
alex says: HELLO WORLD

🧭 Quick Reference

graph TD A["Command Line Input"] --> B["sys.argv"] B --> C["argparse"] C --> D["Validated Arguments"] E["Environment"] --> F["os.environ"] F --> D D --> G["Your Program"] G --> H["sys.exit"]

🚀 You Did It!

You now know how Python:

  • Listens to command line arguments with sys.argv
  • Parses them smartly with argparse
  • Validates types and choices
  • Reads environment variables with os.environ
  • Uses the sys module toolbox

Go build something amazing! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.