Choose text for humans and structured output for scripts.
What It Does and Why It Matters
Readable CLI output can include labels and aligned columns. Machine-readable output should have a stable format such as JSON or CSV without unrelated status messages on stdout. When a program supports both, an explicit --json flag clarifies the contract; send diagnostics to stderr so data pipelines stay parseable.
Version machine-readable schemas carefully; changing a field name can break automation.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import json
result = {"status": "ok", "processed": 3}
print("Processed 3 items")
print(json.dumps(result, sort_keys=True))
How the Code Works
- The imports make these standard-library tools available: json.
- The name result receives the value of {'status': 'ok', 'processed': 3}. Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
Processed 3 items
{"processed": 3, "status": "ok"}
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
This is useful for scripts, maintenance commands and automated workflows. Treat inputs as untrusted, keep normal results separate from errors, and choose exit codes consistently. Keep reusable logic outside the command-line parser so it can be tested independently.
Practice Exercise
Create a format_result(result, as_json) function and test its two output modes.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Mixing progress messages with JSON stdout so that a downstream parser receives invalid input.
- Treating successful output as proof of a successful exit code, or accepting an unchecked path or command argument.
Key Takeaways
- Choose text for humans and structured output for scripts.
- Readable CLI output can include labels and aligned columns.
- Create a format_result(result, as_json) function and test its two output modes.