Python Central HubSign in

Automation and Scripting / Phase 6: Task Scheduling & Deployment

Running Scripts from the Command Line

Run Python automation scripts reliably from the shell, using venvs and predictable working directories.

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.

Basic run

Shell
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__):

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

🧪 Try It Yourself

Exercise 1 – List Files with os.listdir

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 – Join Paths with os.path.join

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 – Write and Read a File

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Was this page helpful?

Let us know how we did