Skip to content

Nov 03: Command Line Scripts

Learning Objectives

After today's class, you should be able to:

  • Name and describe three commands used in the terminal.
  • Explain sys.argv and what command-line arguments are.
  • Summarize what you can do with the os and sys modules.

Reminders

The Command Line

[15 min]

  • Also known as the "command line" or "terminal"
  • Take 10–15 minutes to learn a few commands
  • Important symbols
    • ~ (tilde) means home directory
    • . (dot) means current directory
    • .. (dot dot) means parent directory

Program Arguments

[10 min]

  • Optional arguments can be given to a program on the command line.
  • sys.argv is the list of command-line arguments passed to program.

Example 1: Printing Arguments

print_args.py
1
2
3
4
5
6
7
8
import sys

def main():
    for i, arg in enumerate(sys.argv):
        print(f"argv[{i}] == '{arg}'")

if __name__ == "__main__":
    main()

Walking the File System

[10 min]

  • Demo of the os module and the sys module
  • Step through this program using the debugger

Example 2: Finding Python Files

search.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""Find all Python files in a given directory."""

import os
import sys

def main(path):

    # for each directory starting from path
    for root, dirs, files in os.walk(path):
        print()
        print(f"{root = }")
        print(f"{dirs = }")
        print(f"{files = }")
        print()
        # for each Python file in current directory
        for filename in sorted(files):
            if filename.endswith(".py"):
                filepath = os.path.join(root, filename)
                print(filepath)

if __name__ == "__main__":
    if len(sys.argv) == 1:
        # no arguments; use current directory
        main(".")
    else:
        # use the "first" command-line argument
        main(sys.argv[1])

In-Class Practice

[15 min]

Exercise

Implement the wc command on Unix systems:

  • Write a command line script named word_count.py.
  • If no arguments are given, print the following message:
    print("Usage: python word_count.py FILE [FILE ...]")
    print("Count lines, words, and chars in each file.")
    
  • For each command line argument:
    • Check if os.path.exists() before opening the file.
    • Count how many lines, words, and chars are in the file.
    • Print the results in this format:
      print(f"{line_count:5d} {word_count:5d} {char_count:5d} {path}")