MODULE 00.1 · PUBLISHED · ~1–2h

Python Logic, Shell & Environment Setup

Set up an isolated Python environment across macOS, Linux, Windows CMD, or PowerShell, validate environment config, and build a CLI file checker with honest exit codes.

When people picture AI engineering, they usually think of prompts, models, and chat interfaces. In practice, Forward Deployed AI Engineers spend their first days on a customer project inside a terminal, inspecting raw data files, checking server environments, and writing small scripts to verify what is actually on disk before any AI model touches it.

If your local setup is messy or your scripts fail silently, debugging an AI pipeline becomes ten times harder. Module 00.1 builds the four foundational habits every engineer needs before writing API calls or agents.

Prerequisites

  • Python 3 (3.11+ recommended): Installed from python.org or your OS package manager and callable from a terminal.
  • Git: Installed from git-scm.com so you can initialize a local repository at the end of the lab.
  • A code editor: Such as VS Code, Cursor, or another plain-text editor you are comfortable with.
  • Terminal access: macOS/Linux Terminal, Windows Command Prompt (CMD), or Windows PowerShell, plus comfort creating folders and moving between directories.

Why These Four Habits Matter

  • Virtual environments (.venv) prevent dependency conflicts: Different projects often require different versions of the same Python library. Creating an isolated .venv folder inside each project keeps its packages separate from your system Python so updating one project never breaks another.
  • Terminal & shell fluency lets you work anywhere: Customer servers rarely have a graphical desktop, only a command line. Knowing how to navigate folders, run scripts, and check exit codes is essential for deploying and troubleshooting real systems.
  • Environment variables (.env vs. .env.example) protect secrets: Hardcoding API keys, passwords, or customer URLs directly inside Python files risks leaking credentials into Git history. Instead, keep sensitive or local values out of source control and document expected variables in .env.example.
  • Exit codes (0, 1, 2) keep automation honest: Every terminal command returns an exit status when it finishes. 0 means success, while non-zero codes signal errors or invalid usage so scripts and pipelines do not silently treat failures as success.

Hands-On Lab: Build Your First FDE Utility

Before feeding log files, customer tickets, or records into an AI pipeline, an engineer needs a reliable way to check whether an input file exists, how many non-empty lines it contains, and whether it exceeds a warning threshold. Core exercise: 25–30 minutes. Full completion, including setup and Git: 1–2 hours.

Step 0: Verify Python and Git Are Installed

Open your terminal and check that both Python and Git are available before creating your project folder:

# macOS / Linux
python3 --version
git --version

# Windows (CMD or PowerShell)
py --version
git --version

On Windows, py is generally more reliable than python3. If either tool is missing, install it first and reopen your terminal.

Step 1: Create a Project Folder and Virtual Environment

Create a folder named fde-00-1, move into it, and create/activate .venv using the commands for your environment:

# 1. Create and enter the project folder
mkdir fde-00-1
cd fde-00-1

# 2A. macOS / Linux
python3 -m venv .venv
source .venv/bin/activate

# 2B. Windows Command Prompt (CMD)
py -m venv .venv
.venv\Scripts\activate.bat

# 2C. Windows PowerShell
py -m venv .venv
.\.venv\Scripts\Activate.ps1

Troubleshooting setup snags:

  • PowerShell blocks script execution: If PowerShell says running scripts is disabled on this system, run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser once, then run .\.venv\Scripts\Activate.ps1 again.
  • Ubuntu / Debian missing ensurepip: If you see an error about ensurepip not being available, install python3-venv via sudo apt install python3-venv and repeat the venv creation command.

Step 2: Create line_check.py

Inside fde-00-1, create line_check.py and paste the script below:

import os
import sys
from pathlib import Path


def count_non_empty_lines(file_path: Path) -> int:
    # 1. Tell "missing" apart from "exists but is a folder"
    if not file_path.exists():
        raise FileNotFoundError(f"Input file not found: {file_path}")
    if not file_path.is_file():
        raise IsADirectoryError(f"Not a file: {file_path}")

    # 2. Read line by line and ignore blank/whitespace-only lines.
    #    "utf-8-sig" reads normal UTF-8 and also skips the invisible marker
    #    (BOM) that some Windows editors put at the start of a file.
    count = 0
    with file_path.open("r", encoding="utf-8-sig") as handle:
        for line in handle:
            if line.strip():
                count += 1
    return count


def main() -> int:
    # 3. Read and validate warning threshold from environment (default: 1000)
    try:
        max_lines = int(os.getenv("MAX_LINES_WARN", "1000"))
        if max_lines < 0:
            raise ValueError("MAX_LINES_WARN cannot be negative")
    except ValueError as exc:
        print(f"Invalid configuration: {exc}", file=sys.stderr)
        return 2

    # 4. Make sure the user passed a file path in the terminal command
    if len(sys.argv) < 2:
        print("Usage: python line_check.py <path-to-file>", file=sys.stderr)
        return 2

    target = Path(sys.argv[1])
    try:
        total = count_non_empty_lines(target)
    except UnicodeDecodeError:
        # The file exists but is not UTF-8 text (for example UTF-16 or binary)
        print(f"Error: {target} is not UTF-8 text", file=sys.stderr)
        return 1
    except OSError as exc:
        # OSError covers missing files, folders and permission problems
        # (FileNotFoundError, IsADirectoryError, PermissionError are subclasses)
        print(f"Error: {exc}", file=sys.stderr)
        return 1

    print(f"Non-empty lines: {total}")
    if total > max_lines:
        # Exceeding the threshold warns the user, but is not a script failure (exit 0)
        print(f"Warning: exceeded threshold ({max_lines})", file=sys.stderr)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

How line_check.py works:

  • Fail-fast config & argument checks (return 2): Before touching disk, main() parses MAX_LINES_WARN and confirms a file path was passed in sys.argv. Invalid configuration or CLI usage returns exit code 2.
  • Specific file checks (return 1): count_non_empty_lines() separates a missing path (FileNotFoundError) from a folder path (IsADirectoryError), and main() catches UnicodeDecodeError so non-UTF-8 files produce a clean one-line error instead of a stack trace.
  • stdout vs. stderr separation: Normal results (Non-empty lines: 3) print to standard output (stdout), while warnings and errors use file=sys.stderr so downstream scripts can parse stdout without mixing diagnostic text into the data.
  • Warnings do not fail the run (return 0): Exceeding MAX_LINES_WARN prints a warning to stderr while still returning 0 because the file was read and counted successfully.

Step 3: Create sample.txt and Run the Tests

With your virtual environment active, create sample.txt using Python so it is saved cleanly as UTF-8 (avoid echo ... > sample.txt in older Windows PowerShell versions, which can write UTF-16 and trigger a non-UTF-8 error):

python -c "open('sample.txt','w',encoding='utf-8').write('one\n\ntwo\n\nthree\n')"

Run these test cases and compare against the expected terminal output:

# Test 1: Valid file (exit code 0)
python line_check.py sample.txt
# Expected output:
# Non-empty lines: 3

# Test 2: Missing file (exit code 1)
python line_check.py missing.txt
# Expected output:
# Error: Input file not found: missing.txt

# Test 3: Directory instead of a file (exit code 1)
python line_check.py .venv
# Expected output:
# Error: Not a file: .venv

# Test 4: Missing argument (exit code 2)
python line_check.py
# Expected output:
# Usage: python line_check.py <path-to-file>

Check the exit code right after a command in your shell:

# macOS / Linux
echo $?

# Windows Command Prompt (CMD)
echo %errorlevel%

# Windows PowerShell
$LASTEXITCODE

Test 5: Exceeding MAX_LINES_WARN (separates stdout and stderr, exit code stays 0):

# macOS / Linux (single command)
MAX_LINES_WARN=2 python line_check.py sample.txt

# Windows CMD (clear after testing)
set "MAX_LINES_WARN=2" && python line_check.py sample.txt
set MAX_LINES_WARN=

# Windows PowerShell (remove after testing)
$env:MAX_LINES_WARN="2"; python line_check.py sample.txt
Remove-Item Env:MAX_LINES_WARN
  • Non-empty lines: 3 → stdout
  • Warning: exceeded threshold (2) → stderr
  • Exit code → 0 (verify with your shell’s exit-code command right after running)

Test 6: Invalid configuration (exit code 2) and clearing the test variable:

# macOS / Linux (scoped to just this single command)
MAX_LINES_WARN=abc python line_check.py sample.txt

# Windows CMD (quotes prevent a trailing space from joining "abc"; second line clears it)
set "MAX_LINES_WARN=abc" && python line_check.py sample.txt
set MAX_LINES_WARN=

# Windows PowerShell (second line removes the variable from the session)
$env:MAX_LINES_WARN="abc"; python line_check.py sample.txt
Remove-Item Env:MAX_LINES_WARN

# Expected terminal output:
# Invalid configuration: invalid literal for int() with base 10: 'abc'

Run your shell’s exit-code check immediately after the command and confirm that it returns 2. On Windows, setting MAX_LINES_WARN persists for the rest of that terminal window until cleared, so always run the cleanup command afterward.

Step 4: Add .env.example and .gitignore

Create .env.example containing MAX_LINES_WARN=1000 and .gitignore containing .venv/ and .env. Note that Python’s os.getenv() reads environment variables from your shell or OS. It does not automatically load .env or .env.example files from disk. Here, .env.example simply documents expected variables, and automatic .env loading belongs in a later lesson.

Step 5: Initialize Git and Commit Your Work

Initialize a local Git repository in fde-00-1, configure a local Git author identity if you have not set one globally yet, stage your project files, and inspect git status before committing:

git init
git config user.name "Your Name"
git config user.email "you@example.com"
git add line_check.py .env.example .gitignore
git status
git commit -m "Complete FDE module 00.1"

In git status, verify that line_check.py, .env.example, and .gitignore are listed under Changes to be committed, while .venv/ and .env do not appear at all. Seeing sample.txt listed under Untracked files is expected because it is only local scratch test data, so leave it uncommitted (or delete it after testing).

Failure Notes & Done When

  • Forgetting to clear a test env var on Windows: Leaving MAX_LINES_WARN=abc set in CMD or PowerShell causes subsequent runs in that shell to exit with code 2.
  • Treating warnings as failures: Exceeding MAX_LINES_WARN prints a warning to stderr but still exits with 0 because the file was read and counted successfully.
  • Done when: You have initialized Git in fde-00-1, committed line_check.py, .env.example, and .gitignore (with .venv/ and .env excluded), and verified exit codes 0, 1, and 2 in your terminal.

Author: Vardaan · Tested on Python 3.12 (macOS, Ubuntu Linux, and Windows PowerShell). Windows CMD commands are included as reference and have not been independently tested end to end.

Practice assignment

Build this

Extend your line_check.py utility in fde-00-1 with one real-world improvement: add support for an optional MIN_LINES_WARN environment variable (defaulting to 1) that prints a warning to stderr if a file has fewer non-empty lines than MIN_LINES_WARN while still exiting with code 0. Verify invalid values like MIN_LINES_WARN=abc exit with code 2, clean up your test environment variables, and commit the updated script to your local Git repository.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why should you create a separate .venv virtual environment for each project instead of installing packages globally?
  2. Does Python automatically read variables from a .env or .env.example file on its own? How does line_check.py read MAX_LINES_WARN right now?
  3. What is the difference between stdout and stderr, and why do we send error messages and warnings to stderr?
  4. In line_check.py, what do exit codes 0, 1, and 2 each tell the shell or calling pipeline?
  5. Why does exceeding MAX_LINES_WARN print a warning while still returning exit code 0 instead of 1?
Reveal self-review answers (attempt the questions first)
  1. Virtual environments: Isolating dependencies per project prevents version conflicts between projects and keeps your system Python clean.
  2. .env loading: No. Python's os.getenv() only reads variables set in your OS or shell environment. Right now, .env.example is documentation only, and line_check.py falls back to 1000 unless MAX_LINES_WARN is set in your terminal.
  3. stdout vs. stderr: stdout carries normal program output (the line count), while stderr carries warnings and error messages. Keeping them separate means another command or pipeline can read stdout cleanly without mixing error text into the data.
  4. Exit codes: 0 means success; 1 means a runtime/file error (such as a missing file, a directory path, or non-UTF-8 text); 2 means invalid usage or invalid configuration.
  5. Warnings vs. failures: Exceeding MAX_LINES_WARN is a threshold alert, not a script crash. Because the file was read and counted properly, returning 0 lets pipelines continue while operators still see the warning on stderr.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.