How does ^C work in Python?

Dan Drown dan-ntp at drown.org
Tue Sep 27 18:29:26 UTC 2016


Quoting Hal Murray <hmurray at megapathdsl.net>:
> dan-ntp at drown.org said:
>> Does python have an option to just exit with the sigint   signal handler and
>> not rely on the interpreter state?
>
> That works for "ntpq -p", but there are two cases in ntpq where that isn't
> good enough.
>
> One is when running in interactive mode.  I suppose that could be fixed by
> running each command in a separate thread.  If ^C happens, kill that thread
> and ignore it.
>
> The other is the mrulist command.  It's two loops.  One to collect the info
> and another to print it out.  (there may be a sort in between)  ^C during the
> first loop is supposed to stop collecting, then print what has been  
> collected.

So, one way to fix this would be to use a library that calls  
poll/select from python, and interruptions are returned back into  
python.

For instance: http://www.dnspython.org/

Downside is that it takes more code to do the lookup:

import dns.resolver

a_records = dns.resolver.query("example.com","A")
aaaa_records = dns.resolver.query("example.com","AAAA")
# merge A/AAAA records here.


Upside is ^C works properly:

^C Traceback (most recent call last):
...
   File "/usr/lib/python2.7/site-packages/dns/query.py", line 70, in _poll_for
     event_list = pollable.poll(long(timeout * 1000))
KeyboardInterrupt




More information about the devel mailing list