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.argvand what command-line arguments are. - Summarize what you can do with the
osandsysmodules.
Reminders¶
- Read: Week 11 (due Nov 04)
- Code: Project 2 (due Nov 11)
- Part A due Tuesday, Nov 4
The Command Line¶
[15 min]
- Also known as the "command line" or "terminal"
- Take 10–15 minutes to learn a few commands
- Tutorial by Django Girls (for beginners)
- Tutorial by Real Python (more advanced)
- 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.argvis the list of command-line arguments passed to program.
Example 1: Printing Arguments
| print_args.py | |
|---|---|
1 2 3 4 5 6 7 8 | |
Walking the File System¶
[10 min]
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 | |
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}")
- Check if