Handle cancellation without leaving half-finished work behind.
What It Does and Why It Matters
Ctrl+C normally raises KeyboardInterrupt in the main thread. Catch it at an appropriate top-level boundary, stop ongoing work and let context managers close files. Prefer saving work using atomic operations rather than rewriting the only copy in place. Do not turn every cancellation into a silent success.
SIGTERM and SIGINT handling differs across operating systems; do not assume Unix signal semantics on Windows.
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.
def run_job(cancelled=False):
try:
if cancelled:
raise KeyboardInterrupt
return "completed"
except KeyboardInterrupt:
return "cancelled"
print(run_job(False))
print(run_job(True))
How the Code Works
- The definition of run_job creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The structured block controls error handling or resource lifetime, including what happens when an operation fails.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
completed
cancelled
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
Wrap a temporary-file write in with and simulate a cancellation before the final replacement.
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
- Swallowing KeyboardInterrupt and reporting that the operation completed successfully.
- Overlooking the documented condition: ctrl+C normally raises KeyboardInterrupt in the main thread.
Key Takeaways
- Handle cancellation without leaving half-finished work behind.
- Ctrl+C normally raises KeyboardInterrupt in the main thread.
- Wrap a temporary-file write in with and simulate a cancellation before the final replacement.