Programming with Python · free preview
Command-Line Programs
Use the values of command-line arguments in a program. Handle flags and files separately in a command-line program. Read data from standard input in a program so that it can be used in a pipeline.
1. Overview
Overview
2. Switching to Shell Commands
Switching to Shell Commands
3. Command-Line Arguments
Command-Line Arguments
4. Running Versus Importing
Running Versus Importing
5. The Right Way to Do It
The Right Way to Do It
6. Handling Multiple Files
Handling Multiple Files
7. The Right Way to Do It
The Right Way to Do It
8. Handling Command-Line Flags
Handling Command-Line Flags
9. Handling Standard Input
Handling Standard Input
10. Arithmetic on the Command Line
Arithmetic on the Command Line
11. Finding Particular Files
Finding Particular Files
12. Changing Flags
Changing Flags
13. Adding a Help Message
Adding a Help Message
14. Adding a Default Action
Adding a Default Action
15. A File-Checker
A File-Checker
16. Counting Lines
Counting Lines
17. Generate an Error Message
Generate an Error Message
18. Read the command-line arguments
For sys.argv = ['readings.py', '--mean', 'small-01.csv'], what are sys.argv[0], sys.argv[1], and sys.argv[2]? Answer comma-separated.
19. Trace a testable readings CLI with a mean action
Predict what demo_data = [[0, 0, 1], [0, 1, 2]] produces for process(demo_data, '--mean'), then predict the sys.argv list for the local command python readings.py --mean small-01.csv. Run the program and compare both predictions.
Example. Trace a testable readings CLI with a mean action
Problem. Predict what demo_data = [[0, 0, 1], [0, 1, 2]] produces for process(demo_data, '--mean'), then predict the sys.argv list for the local command python readings.py --mean small-01.csv. Run the program and compare both predictions.
Correct solution.
import sys
import numpy
def process(source, action):
if isinstance(source, str):
data = numpy.loadtxt(source, delimiter=',')
else:
data = numpy.asarray(source, dtype=float)
if action == '--min':
values = numpy.min(data, axis=1)
elif action == '--mean':
values = numpy.mean(data, axis=1)
elif action == '--max':
values = numpy.max(data, axis=1)
else:
raise ValueError('action must be --min, --mean, or --max')
return [float(value) for value in values]
def main(argv):
if len(argv) == 1:
print('usage: python readings.py action [filenames]')
return
action = argv[1]
filenames = argv[2:]
for filename in filenames:
print(filename, process(filename, action))
if __name__ == '__main__':
main(sys.argv)Browser-safe call and trace。
demo_data = [[0, 0, 1], [0, 1, 2]]
print(process(demo_data, '--mean'))Output
[0.3333333333333333, 1.0]Local command trace.```bash $ python readings.py --mean small-01.csv
- `sys.argv` is `['readings.py', '--mean', 'small-01.csv']`.
- `main` reads `action = '--mean'` and `filenames = ['small-01.csv']`.
- `numpy.mean(..., axis=1)` computes each row mean.
- The output is `small-01.csv [0.3333333333333333, 1.0]`.
Failure case.```python
process(demo_data, '--average')Output
ValueError: action must be --min, --mean, or --max关键提醒。
The script separates argument parsing from data processing, so it can be tested inside the browser with an inline list and run locally with real filenames. The __name__ guard keeps import side effects out of the browser trace. The action check rejects invalid flags before file work begins.
20. Retrieval practice
For the local command python readings.py --max small-01.csv small-02.csv small-03.csv, state the complete sys.argv list, the action variable, the filename list, and what the program does if no filenames follow --max.
Answer with the argv positions, not a general description of command-line tools.
21. Mastery check
Apply the CLI to the new input python readings.py --mean with the two CSV rows 0,0,1 and 0,1,2 supplied on standard input. Give the expected two-line output, the stdin branch your program must use, and the sys.argv list it sees in that invocation.
Include the stdin branch, the exact expected values, and the traceback risk avoided by checking filename length.
Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free