Skip to content

Running Scripts from the Command Line

Basic run

python my_script.py
python my_script.py

Use a virtual environment

  • isolate dependencies
  • avoid β€œworks on my machine”

Working directory tip

Many scripts break because they assume the current directory.

Prefer pathlib.Path(__file__)pathlib.Path(__file__):

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

πŸ§ͺ Try It Yourself

Exercise 1 – List Files with os.listdir

Exercise 2 – Join Paths with os.path.join

Exercise 3 – Write and Read a File

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did