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 12)
- Part A due Wed, Nov 5
- Part B due Tue, Nov 11
Hints on PA2, Part A¶
[10 min]
-
See Clarifications posted this morning
- In particular, update
test_read_file()
- In particular, update
-
Turn on type hint checking
- Press F1 to open the command pallette.
- Type
work jsonand press Enter.- This will open a file named
settings.json.
- This will open a file named
- Add/update the following settings between the curly braces:
"editor.rulers": [100], "python.analysis.typeCheckingMode": "basic", - And after
".",under"python.testing.pytestArgs"add:"-v",- This will make the pytest output more verbose (helpful)
-
Do not "hard code" file paths
- For example, don't do this:
# WRONG, the CS149/PA2 folder won't exist on Gradescope! with open("CS149/PA2/log.txt") as file: ... - Instead, use this pattern to get the "current" path:
path = os.path.join(os.path.dirname(__file__), "log.txt") with open(path) as file: ...
- For example, don't do this:
The Command Line¶
[5 min]
- Also known as the "command line" or "terminal"
- Take time after class 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¶
[5 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¶
[20 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