<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>stacyprowell.com &#187; break</title>
	<atom:link href="http://stacyprowell.com/blog/tag/break/feed/" rel="self" type="application/rss+xml" />
	<link>http://stacyprowell.com/blog</link>
	<description>Ugh, Stacy's talking again...</description>
	<lastBuildDate>Tue, 27 Apr 2010 20:09:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Trapping CTRL+C in Python</title>
		<link>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/</link>
		<comments>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 18:12:30 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[break]]></category>
		<category><![CDATA[ctrl+c]]></category>
		<category><![CDATA[interrupt]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=123</guid>
		<description><![CDATA[I&#8217;ve been doing some nasty database work with Python and MySQL.  Specifically, I&#8217;ve got long programs that run eight to ten hours, and sometimes I need to kill them and restart them later.
So&#8230; I wanted a way to trap CTRL+C and clean up.  That is, I wanted to have transactions without actually having to use [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-126" title="1ebeb1d2f212046a4e47fcd414dbad9b1" src="http://stacyprowell.com/blog/wp-content/uploads/2009/03/1ebeb1d2f212046a4e47fcd414dbad9b1-150x150.jpg" alt="1ebeb1d2f212046a4e47fcd414dbad9b1" width="150" height="150" />I&#8217;ve been doing some nasty database work with Python and MySQL.  Specifically, I&#8217;ve got long programs that run eight to ten hours, and sometimes I need to kill them and restart them later.</p>
<p>So&#8230; I wanted a way to trap CTRL+C and clean up.  That is, I wanted to have transactions without actually having to use transactions.  I&#8217;m funny that way.  (In other news, I&#8217;m probably moving to PostgreSQL at some point.)</p>
<p>Anyway, here&#8217;s what I came up with.  You might find it useful, too.<span id="more-123"></span></p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/python -i</span>
&nbsp;
<span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
Trap keyboard interrupts.  No rights reserved; use at your own risk.
&nbsp;
@author: Stacy Prowell (http://stacyprowell.com)
'</span><span style="color: #483d8b;">''</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">signal</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> BreakHandler:
    <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
    Trap CTRL-C, set a flag, and keep going.  This is very useful for
    gracefully exiting database loops while simulating transactions.
&nbsp;
    To use this, make an instance and then enable it.  You can check
    whether a break was trapped using the trapped property.
&nbsp;
    # Create and enable a break handler.
    ih = BreakHandler()
    ih.enable()
    for x in big_set:
        complex_operation_1()
        complex_operation_2()
        complex_operation_3()
        # Check whether there was a break.
        if ih.trapped:
            # Stop the loop.
            break
    ih.disable()
    # Back to usual operation...
    '</span><span style="color: #483d8b;">''</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, emphatic=<span style="color: #ff4500;">9</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Create a new break handler.
&nbsp;
        @param emphatic: This is the number of times that the user must
                    press break to *disable* the handler.  If you press
                    break this number of times, the handler is automagically
                    disabled, and one more break will trigger an old
                    style keyboard interrupt.  The default is nine.  This
                    is a Good Idea, since if you happen to lose your
                    connection to the handler you can *still* disable it.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">False</span>
        <span style="color: #008000;">self</span>._emphatic = emphatic
        <span style="color: #008000;">self</span>._oldhandler = <span style="color: #008000;">None</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _reset<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Reset the trapped status and count.  You should not need to use this
        directly; instead you can disable the handler and then re-enable it.
        This is better, in case someone presses CTRL-C during this operation.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count = <span style="color: #ff4500;">0</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> enable<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Enable trapping of the break.  This action also resets the
        handler count and trapped properties.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #008000;">self</span>._enabled:
            <span style="color: #008000;">self</span>._reset<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">True</span>
            <span style="color: #008000;">self</span>._oldhandler = <span style="color: #dc143c;">signal</span>.<span style="color: #dc143c;">signal</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">signal</span>.<span style="color: black;">SIGINT</span>, <span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> disable<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Disable trapping the break.  You can check whether a break
        was trapped using the count and trapped properties.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._enabled:
            <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">False</span>
            <span style="color: #dc143c;">signal</span>.<span style="color: #dc143c;">signal</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">signal</span>.<span style="color: black;">SIGINT</span>, <span style="color: #008000;">self</span>._oldhandler<span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._oldhandler = <span style="color: #008000;">None</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, signame, sf<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        An break just occurred.  Save information about it and keep
        going.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count += <span style="color: #ff4500;">1</span>
        <span style="color: #808080; font-style: italic;"># If we've exceeded the &quot;emphatic&quot; count disable this handler.</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._count <span style="color: #66cc66;">&gt;</span>= <span style="color: #008000;">self</span>._emphatic:
            <span style="color: #008000;">self</span>.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__del__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Python is reclaiming this object, so make sure we are disabled.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    @<span style="color: #008000;">property</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> count<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        The number of breaks trapped.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._count
&nbsp;
    @<span style="color: #008000;">property</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> trapped<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Whether a break was trapped.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._count <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">0</span></pre></div></div>

<p>To use this, make an instance and then enable the instance.  If you repeatedly hit CTRL+C you will eventually disable it (see <tt>emphatic</tt> in the <tt>__init__</tt>).</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Trap break.</span>
bh = BreakHandler<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
bh.<span style="color: black;">enable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> item <span style="color: #ff7700;font-weight:bold;">in</span> big_set:
    <span style="color: #ff7700;font-weight:bold;">if</span> bh.<span style="color: black;">trapped</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Stopping at user request (keyboard interrupt)...'</span>
        <span style="color: #ff7700;font-weight:bold;">break</span>
    do_thing_1<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    do_thing_2<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    do_thing_3<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
do_cleanup<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
bh.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>If you press CTRL+C, it is detected at the <em>start</em> of the loop, and break is called.  Then <tt>do_cleanup()</tt> runs, and the break handler is disabled, returning things to normal.  The idea is that <tt>do_thing_1()</tt>, <tt>do_thing_2()</tt>, and <tt>do_thing_3()</tt> all run to completion, even when the user presses CTRL+C, and <tt>do_cleanup()</tt> always runs when the loop is exited.</p>
<p>I consider this public domain; if you like it, use it. If you don&#8217;t like it, don&#8217;t use it. If you have suggestions, please leave me a comment.<!--more--></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F03%2F30%2Ftrapping-ctrlc-in-python%2F&amp;linkname=Trapping%20CTRL%2BC%20in%20Python"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
