Wednesday, May 20, 2026
Cohort 3 | Project CloudIgnite Topics: File Handling, JSON Modules, System Administration with Python, Debugging in VS Code Duration: ~3 hours
Key Takeaways
- File handler module: reusable JSON reader with
try/except;json.load()converts to dict - SysAdmin with Python:
subprocess.run()replaces deprecatedos.system()for shell commands - User management:
adduser,userdel,usermod -aGvia Python subprocess - Command-line arguments:
sys.argv[1]for script arguments - Piping in Python:
sp.run(["ls"], capture_output=True)then pass stdout to next command - VS Code debugging: breakpoints (red dots), Watch panel for variable inspection
- Key rule: simple tasks → Bash; complex logic → Python
1. File Handling & JSON Modules
Reading a JSON File with a Module
The session demonstrated how to build a reusable file handler module (json_file_handler.py) instead of writing file-reading logic directly in your main script.
Key pattern:
import json
def read_json_file(file_name):
data = ""
try:
with open(file_name) as f:
data = json.load(f) # Converts JSON content → Python dictionary
except:
print("Could not read file")
return data
Why with open(...) ?
- Automatically closes the file when you exit the
withblock — even if you forget to call.close().
Why try/except?
- The file might not exist, or it might be corrupted.
- Without it, the program crashes. With it, you handle the error gracefully.
Why json.load() instead of reading as plain text?
- Plain
read()returns a raw string. json.load()converts the file content directly into a Python dictionary, making data easy to work with.
Using the Module in a Main Script
import json_file_handler
data = json_file_handler.read_json_file("files/insulin.json")
if data != "":
b_insulin = data["molecules"]["B insulin"]
a_insulin = data["molecules"]["A insulin"]
actual_insulin = b_insulin + a_insulin
else:
print("Error: Exiting program")
Alternative import syntax:
from json_file_handler import read_json_file
# Then call directly: read_json_file("files/insulin.json")
Common errors encountered:
| Error | Cause | Fix |
|---|---|---|
ModuleNotFoundError | Module file name doesn't match import name | Ensure filenames match exactly (case-sensitive) |
None type is not subscriptable | data is empty/None before indexing | Check file path; print data to debug |
Could not read file | Wrong file path used | Remove or correct subfolder prefix in path |
Dictionary Comprehension (One-liner vs Multi-line)
One-liner:
aa_count = {x: float(insulin.upper().count(x)) for x in key_list}
Multi-line (easier to read):
aa_count = {}
for i in key_list:
aa_count[i] = insulin.upper().count(i)
Both produce the same result. Multi-line is more beginner-friendly.
Computing Molecular Weight & Error
molecular_weight_insulin_sum = sum(molecular_weight_insulin.values())
diff = molecular_weight_insulin_sum - molecular_weight_insulin_actual
error = 100 * diff / molecular_weight_insulin_actual
print(f"Molecular Weight of Insulin: {molecular_weight_insulin_sum}")
print(f"Percentage Error: {error}")
2. System Administration with Python
What is System Administration (SysAdmin)?
System administration is the management of hardware, software, and systems to ensure smooth operation. Common tasks include:
- Installing/removing hardware and software
- Creating and managing users and groups
- Managing file permissions
- Maintaining servers and databases
- Responding to system outages and security issues
Python vs Bash for SysAdmin:
| Scenario | Recommended Tool |
|---|---|
| Simple, repetitive commands | Bash |
| Complex logic, conditions, calculations | Python |
Python can do everything the Linux module covered — using the
osandsubprocessmodules to communicate with the OS.
Key Python Modules for SysAdmin
| Module | Use |
|---|---|
os | Interact with the OS (files, directories, system calls) |
subprocess | Execute shell commands with more control than os.system |
Note:
os.system()is now deprecated. Prefersubprocess.run().
Managing Users
Create a new user (with confirmation loop):
import os
def new_user():
confirm = "n"
while confirm.lower() != "y":
username = input("Enter the name of the user to add: ")
confirm = input("Confirm? (Y/N): ")
os.system(f"sudo adduser {username}")
Remove a user:
def remove_user():
confirm = "n"
while confirm.lower() != "y":
username = input("Enter username to remove: ")
confirm = input("Confirm? (Y/N): ")
os.system(f"sudo userdel {username}")
Command-Line Arguments with sys
import sys
arg1 = sys.argv[1]
if arg1 == "C":
new_user()
elif arg1 == "R":
remove_user()
else:
print("Invalid argument")
Run from terminal:
python3 sysutils.py C # Create user
python3 sysutils.py R # Remove user
Adding a User to a Group (subprocess)
import subprocess as sp
result = sp.run(["groups"], stdout=subprocess.PIPE)
# stdout=PIPE captures output into variable instead of printing to terminal
chosen_groups = input("Enter groups (space-separated): ").split()
for group in chosen_groups:
confirm = input(f"Add user to {group}? (Y/N): ")
if confirm.lower() == "y":
sp.run(["sudo", "usermod", "-aG", group, username])
Installing / Removing Packages
import os
def manage_packages():
while True:
action = input("Install (I) or Remove (R)? ").upper()
if action in ["I", "R"]:
break
packages = input("Enter package names (space-separated): ")
if action == "I":
os.system(f"sudo apt install {packages}")
elif action == "R":
os.system(f"sudo apt remove {packages}")
Package manager reference:
| OS | Install Command |
|---|---|
| Ubuntu / Debian | apt or apt-get |
| Amazon Linux | yum |
Using subprocess.run() (Lab 128)
import subprocess as sp
# Run `ls` command
sp.run(["ls"])
# Run `ls -la`
sp.run(["ls", "-la"])
# Run `ls -la README.md`
sp.run(["ls", "-la", "README.md"])
# Get system info
sp.run(["uname", "-a"])
# List active processes
sp.run(["ps", "-x"])
Capturing output & piping (Python equivalent of |):
result = sp.run(["ls"], capture_output=True)
sp.run(["grep", "README"], input=result.stdout)
This is the Python equivalent of
ls | grep READMEin the terminal.
Common SysAdmin Commands (via Python)
| Task | Linux Command | Python equivalent |
|---|---|---|
| List files | ls -la | sp.run(["ls", "-la"]) |
| System info | uname -a | sp.run(["uname", "-a"]) |
| Active processes | ps -x | sp.run(["ps", "-x"]) |
| Create user | sudo adduser <name> | os.system(f"sudo adduser {name}") |
| Delete user | sudo userdel <name> | os.system(f"sudo userdel {name}") |
| Update packages | sudo apt upgrade | os.system("sudo apt upgrade") |
3. Debugging in VS Code
Setting Up the Debugger
- Open the Run and Debug panel (left sidebar icon, or
Ctrl+Shift+D) - Click Run and Debug
- Select Python Debugger → Python File
Breakpoints
- Click to the left of a line number to place a red dot (breakpoint)
- The program will pause at that line when running in debug mode
- Step through code line by line using the debug controls
Watchers
- In the debug panel, find the Watch section
- Click + to add a variable name (e.g.
name,age) - The watcher shows the live value of that variable as you step through
Why use the debugger? Instead of adding
print()statements everywhere, the debugger lets you inspect variable values at any point in execution without modifying your code.
Key Takeaways
- Build reusable modules (e.g. file handler) instead of writing everything in one file
- Always use
try/exceptwhen reading files — files may be missing or corrupted with open()is the safest way to open files (auto-closes)subprocess.run()is the modern, preferred way to run OS commands from Python (replaces deprecatedos.system())- Python can replicate virtually everything done in the Linux module
- For simple tasks → Bash; for complex logic → Python
- Use VS Code's debugger and watchers to step through code and inspect variables
🎓 AWS Certified Cloud Practitioner (CLF-C02) Relevance
The following content from today's lecture touches on concepts that appear in the CLF-C02 exam:
✅ Relevant Topics
| Lecture Topic | CLF-C02 Domain | Notes |
|---|---|---|
| AWS Cloud9 (browser-based IDE used in labs) | Domain 3: Cloud Technology & Services | Cloud9 is an AWS managed development environment — understanding it as a cloud service is relevant |
| Amazon EC2 instances (used to run Cloud9 and host Python challenges) | Domain 3: Cloud Technology & Services | EC2 is a core compute service tested in CLF-C02 |
| AWS Single Sign-On (SSO) / authentication tokens (mentioned when downloading lab files) | Domain 4: Billing, Pricing & Support / Security | IAM, SSO, and access management are exam topics |
| System administration concepts (managing users, permissions, software) | Domain 2: Security & Compliance | IAM in AWS mirrors OS-level user/group/permission management concepts |
| Stopping/starting lab environments (EC2 instances) | Domain 3: Cloud Technology & Services | Understanding EC2 instance states (stop, start, terminate) is tested |
| Package managers & OS types (Amazon Linux vs Ubuntu/Debian) | Domain 3: Cloud Technology & Services | AWS offers different AMIs (Amazon Machine Images); knowing Amazon Linux is relevant |
❌ Not Directly Relevant to CLF-C02
- Python syntax (json, subprocess, os modules)
- File handling and JSON parsing
- VS Code debugging workflow
- Caesar cipher / algorithm logic
Tip: While Python scripting itself isn't tested in CLF-C02, understanding what AWS services are being used in these labs (EC2, Cloud9, IAM/SSO) is very much exam-relevant. Focus on why these services exist and what problems they solve in the cloud.
Notes compiled from lecture — May 20, 2026 | Cohort 3: Project CloudIgnite