Skip to content

Running Scripts from the Command Line

diagram python script.py and python -m are not the same command mermaid
Both run the same file, but they set up the import system differently. Running a path puts that file's own directory first on sys.path; running a module puts the current directory there instead. That single difference decides whether the file can import the package it lives in.
bash
python my_script.py
  • isolate dependencies
  • avoid “works on my machine”

Many scripts break because they assume the current directory.

Prefer pathlib.Path(__file__):

base_dir.py
from pathlib import Path
 
BASE_DIR = Path(__file__).resolve().parent
print(BASE_DIR)

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading