How to capture KeyboardInterrupt in pytest?
<p>UnitTests has a feature to capture <code>KeyboardInterrupt</code>, finishes a test and then report the results.</p>

<blockquote>
  <p><strong>-c, --catch</strong> </p>
  
  <p><em>Control-C</em> during the test run waits for the current test to end and then reports all the results so far. A second <em>Control-C</em>
  raises the normal KeyboardInterrupt exception.</p>
  
  <p>See Signal Handling for the functions that provide this functionality.</p>
  
  <p>c.f. <a href="https://docs.python.org/2/library/unittest.html#command-line-options" rel="nofollow">https://docs.python.org/2/library/unittest.html#command-line-options</a></p>
</blockquote>

<p>In PyTest, <kbd>Ctrl</kbd>+<kbd>C</kbd> will just stop the session.</p>

<p>Is there a way to do the same as UniTests:</p>

<ul>
<li>Capture <code>KeyboardInterrupt</code></li>
<li>Finishes to execute the on-going test [optional]</li>
<li>Skip other tests</li>
<li>Display a result, and potentially print a report (e.g. usage of <code>pytest-html</code>)</li>
</ul>

<p>Thanks</p>

<p>Take a look at pytest's <a href="http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html" rel="nofollow">hookspec</a>.</p>

<p>They have a hook for keyword interrupt.</p>

<pre><code>def pytest_keyboard_interrupt(excinfo):
""" called for keyboard interrupt. """
</code></pre>

python py.test