Running Scripts from the Command Line
flowchart TD A["python pkg/mod.py"] --> B["sys.path[0] = pkg/"] B --> C["'pkg' itself is NOT importable"] C --> D["from pkg import mod -> ModuleNotFoundError"] E["python -m pkg.mod"] --> F["sys.path[0] = the current directory"] F --> G["'pkg' is importable"] G --> H["relative and absolute imports both work"] I["__name__"] --> J["'__main__' either way -- the guard behaves the same"]
Basic run
Section titled “Basic run”python my_script.pyUse a virtual environment
Section titled “Use a virtual environment”- isolate dependencies
- avoid “works on my machine”
Working directory tip
Section titled “Working directory tip”Many scripts break because they assume the current directory.
Prefer pathlib.Path(__file__):
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
print(BASE_DIR)🧪 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