Scheduling Scripts on Linux/Mac (Cron Jobs)
flowchart LR
A["works in your terminal"] --> B["cron runs it"]
B --> C{"fails?"}
C --> D["PATH is minimal -- 'python' may not resolve"]
C --> E["cwd is HOME, not the project -- relative paths break"]
C --> F["no virtualenv activated -- imports fail"]
D --> G["use an absolute interpreter path: /path/venv/bin/python"]
E --> H["cd in the command, or use absolute paths everywhere"]
F --> G
G --> I["redirect output to a log -- cron mail is easy to miss"]
H --> I
Cron basics
Section titled “Cron basics”Cron runs commands on a schedule.
Common gotchas:
- minimal PATH
- different working directory
Pattern
Section titled “Pattern”- use absolute paths
- redirect outputs
Example crontab entry:
0 9 * * * /usr/bin/python3 /home/user/job.py >> /home/user/job.log 2>&1Use logging in the script, not only stdout.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading