Google IT Automation with Python cheat sheet
Google IT Automation with Python · Keep the key ideas within reach.
Python Programming Fundamentals and Scripting for IT
Immutable types (int, float, str, tuple) cannot be changed in place; reassigning a name rebinds it to a new object. Mutable types (list, dict, set) change in place, so aliases see the change.
String formatting: f-strings (f"{name}: {port}") evaluate expressions at runtime; str.format() and %-formatting are alternatives. Use !r for repr and :>8 to right-align in a width of 8.
Slicing s[start:stop:step] excludes stop; negative indices count from the end. s[::-1] reverses a string; s[1:] drops the first character.
List comprehensions [expr for item in iterable if cond] build a new list; generator expressions use parentheses and yield items lazily, saving memory on large inputs.
dict.get(key, default) avoids KeyError; dict.items() yields (key, value) pairs; dict.setdefault(key, []) appends into a list without a separate existence check.
Exception handling: try/except/else/finally. except catches listed exception classes; else runs only when no exception occurred; finally always runs, including on return.
File I/O: with open(path, "r", encoding="utf-8") as f: closes the file automatically. Modes: r read, w truncate-write, a append, x exclusive create, b binary, + read/write.
Command-line arguments: sys.argv[0] is the script name; argparse.ArgumentParser builds typed options with add_argument("--port", type=int, required=True) and help text.
Module execution guard: code under if name == "main": runs only when the file is executed directly, not when imported as a module.
Managing Files, Processes, and System Resources with Python
os.path vs pathlib: os.path.join, exists, isfile, isdir, getsize are string-based; pathlib.Path("/tmp") / "log.txt" supports .exists(), .read_text(), .glob("*.log"), and .iterdir().
os.walk(top) yields (dirpath, dirnames, filenames) for every directory under top, top-down by default; modify dirnames in place to prune traversal.
shutil.copy2 preserves metadata; shutil.copytree copies directory trees; shutil.move renames or moves; shutil.rmtree deletes a tree recursively and is irreversible.
subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True) returns a CompletedProcess with .stdout, .stderr, .returncode; check=True raises CalledProcessError on non-zero exit.
os.listdir returns names only; os.scandir returns DirEntry objects with .is_file(), .is_dir(), and .stat(), avoiding an extra stat call per entry.
Process info: os.getpid() returns the current PID; os.getppid() the parent; psutil.Process(pid).memory_info().rss gives resident memory in bytes; psutil.cpu_percent(interval=1) samples CPU.
Disk usage: shutil.disk_usage(path) returns total, used, free in bytes; os.stat(path).st_size gives a single file's size; st_mtime is the modification time as a Unix timestamp.
Environment and cwd: os.environ is a mapping of environment variables; os.getcwd() returns the working directory; os.chdir(path) changes it; subprocess cwd= and env= set them per child.
Permissions: os.chmod(path, 0o755) sets mode bits; os.stat(path).st_mode holds them; stat.S_ISDIR(mode) and stat.S_IMODE(mode) test type and permission bits.
Version Control with Git and GitHub Collaboration Workflows
Three states: working tree (edited files), staging area / index (git add), and repository (git commit). git status shows changes in each; git diff shows unstaged, git diff --staged shows staged.
Commit graph: a commit records a tree snapshot plus parent pointers; branches are movable refs to commits. HEAD points to the current branch, and a detached HEAD points directly to a commit.
Merge vs rebase: git merge creates a merge commit joining two histories; git rebase replays commits onto a new base, producing linear history but rewriting commit hashes.
Remote workflow: git fetch downloads objects without changing the working tree; git pull is fetch plus merge (or rebase with pull.rebase); git push uploads local commits to the remote branch.
Undo rules: git restore discards working-tree edits; git restore --staged unstages; git reset --soft keeps changes staged; --mixed unstages; --hard discards working-tree changes.
git revert creates a new commit that inverts an earlier one and is safe on shared branches; git reset rewrites local history and must not be used on pushed commits.
Collaboration on GitHub: fork creates a personal copy; a pull request proposes merging a branch; reviews approve or request changes; protected branches can require passing status checks before merge.
Conflicts occur when both sides change the same lines; Git writes <<<<<<<, =======, >>>>>>> markers, and the file must be edited and git add-ed before committing the resolution.
git log --oneline --graph --all visualizes history; git blame shows the last commit per line; git bisect finds the commit that introduced a bug by binary search.
Automating Real-World IT Tasks with Python, Testing, and Troubleshooting
Automation pattern: read input (files, CSV, API), transform data, act (rename, email, restart, deploy), then verify and log. Idempotent steps can be re-run safely; non-idempotent steps need guards.
CSV handling: csv.reader yields lists; csv.DictReader yields dicts keyed by header; csv.DictWriter with fieldnames and writeheader() writes rows; always open files with newline="" on Windows.
Email automation: smtplib.SMTP(host, port) with starttls() and login() sends via send_message(); email.message.EmailMessage sets subject, from, to, and body; attachments use add_attachment().
Web requests: requests.get(url, timeout=10) returns a Response with .status_code, .text, .json(); call raise_for_status() to raise on 4xx/5xx; retry with exponential backoff on transient errors.
Regular expressions: re.search finds the first match anywhere, re.match only at the start, re.findall returns all matches; use raw strings r"\d+" and named groups (?P...) with groupdict().
unittest: subclass unittest.TestCase; methods test_* run automatically; assertEqual, assertTrue, assertRaises are assertions; setUp/tearDown run before/after each test; run with python -m unittest.
pytest: plain assert statements, fixtures via @pytest.fixture, parametrization via @pytest.mark.parametrize; pytest discovers files named test_*.py and functions named test_*.
Troubleshooting: read the traceback bottom-up for the exception type and line; logging.basicConfig(level=logging.INFO) plus logger.exception() inside except captures the traceback; reproduce with the smallest input.
Scheduling and safety: cron entries run scripts non-interactively, so use absolute paths and log output; wrap destructive operations with dry-run flags and validate paths before deleting or overwriting.