Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Python has its own built-in singal handler for <code>SIGINT</code>. This handler simply raises <code>KeyboardInterrupt</code>. In your first code, you replaced the built-in handler with the new handler hence you see this output:</p> <pre><code>$python test_exc.py ^Cinterrupted </code></pre> <p>Note that <code>io interrupted</code> is <strong>not</strong> printed, since no exception was raised. In fact modifying the code to:</p> <pre><code>import signal,sys def handleInt(sign,no): print "interrupted" signal.signal(signal.SIGINT, handleInt) # exception raised is IOError try: sys.stdin.read(1) except IOError: print "io interrupt" else: # else is executed only if no exception was raised print "done" </code></pre> <p>You get:</p> <pre><code>$python test_exc.py ^Cinterrupted done </code></pre> <p>Note that hitting <code>Ctrl+C</code> does <em>not</em> block the call to <code>sys.stdin.read(1)</code> hence you still have to press some key to let the program continue. Raising an exception inside the signal handler will raise it as if the call to <code>sys.stdin.read(1)</code> produced it:</p> <pre><code>import signal,sys def handleInt(sign,no): print "interrupted" raise OSError signal.signal(signal.SIGINT, handleInt) # exception raised is IOError try: sys.stdin.read(1) except IOError: print "io interrupt" else: # else is executed only if no exception was raised print "done" </code></pre> <p>Sample run:</p> <pre><code>$python test_exc.py ^Cinterrupted Traceback (most recent call last): File "test_exc.py", line 10, in &lt;module&gt; sys.stdin.read(1) File "test_exc.py", line 5, in handleInt raise OSError OSError </code></pre> <hr> <p>Note: you can access the default signal handler via <code>signal.default_int_handler</code>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload