user202729
Put the following in `a.py`:
```
#!/bin/python3
try:
while True: pass
except KeyboardInterrupt:
pass
```
Run with `python a.py`:
```
$ python a.py
```
Press `Ctrl+C` to interrupt it:
```
^CTraceback (most recent call last):
File "/tmp/a.py", line 3, in <module>
while True: pass
KeyboardInterrupt
```
Why is the error still printed and not captured?
Python version: Python 3.11.3, on Linux.
Top Answer
Anonymous 12698
The error message you're seeing ("KeyboardInterrupt") is printed even though it's caught in the `try-except` block for a specific reason. Here's why:
- **`try-except` captures exceptions:** The `try-except` block in your code attempts to capture the `KeyboardInterrupt` exception that occurs when you press Ctrl+C. This part works as expected.
- **Exceptions can't be silenced completely:** However, even if the exception is caught, Python still prints a traceback (the error message with line numbers) by default. This serves as an informative message to the user about what caused the program to interrupt.
**Solutions to avoid the printed error message:**
1. **Use `sys.exit()`:** You can add `sys.exit(0)` inside the `except` block. This will exit the program cleanly without printing the traceback.
```python
#!/bin/python3
try:
while True:
pass
except KeyboardInterrupt:
print("Exiting...") # Optional: Print a custom message
sys.exit(0)
# Run: python a.py
# Press Ctrl+C: Exiting... (no traceback)
```
2. **Suppress printing with context manager (Python 3.3+)**: If you're using Python 3.3 or later, you can leverage the `contextlib.suppress` context manager to suppress the traceback entirely.
```python
from contextlib import suppress
#!/bin/python3
with suppress(KeyboardInterrupt):
while True:
pass
# Run: python a.py
# Press Ctrl+C: (no message, program exits)
```
Both methods achieve a similar outcome: stopping the infinite loop gracefully when interrupted without printing the traceback. Choose the approach that best suits your needs and Python version.
https://ariyadanesh.com/portfolio/%da%a9%d9%88%db%8c%d9%84%d8%b1-%d9%85%d9%81%d8%aa%d9%88%d9%84/
Answer #2
daviewales
I'm not able to reproduce your question.
I copied and pasted your code and ran it, and it exits without printing a traceback.