0

I am trying to empty the list whenever there is a keyboard interrupt but this doesn't work. Below is my code.

while 1:
    try:
       n=0
       while n<10:
           pkt=sniff(prn=lambda x:x.sprintf("{Ether : %ether.src% --> %ether.dst%}"),timeout=1,store=1)
           buffpkt+=pkt[:]  ##Store packets in a list buffer
           n+=1
       self._tempbuffstore(buffpkt)

    except KeyboardInterrupt:
        buffpkt=[]  ##Flush the list asynchronously "THIS IS THE MAIN REQUIREMENT FOR INTERRUPT"
        raise

I tried doing all possible things but this interrupt handler is not working. Any help?

Abhinav
  • 992
  • 2
  • 11
  • 26
  • 1
    "doesn't work" is not very specific. What do you expect? What do you get instead? – jfs Aug 09 '12 at 09:22
  • When I launch it in the shell, it doesn't capture the interrupt and always sniffs the packets and stores it. I want it to flush the list when interrupt occurs. – Abhinav Aug 09 '12 at 09:27

1 Answers1

1

It's looks like you call to 'sniff', which I can't reproduce, is blocking. It's very common for network-related methods.

You should put your sniff method in a separate thread, and then, it's possible to handle your exception in the main loop (and you'll also have to deal with stopping the thread on exceptions).

Alexis Huet
  • 755
  • 4
  • 11
  • I already have sniff function in a thread. But I want to clear the buffer in the function of that thread by Keyboard Interrupt. – Abhinav Aug 09 '12 at 09:49
  • 1
    The cleaner way to do it is to use the [logging](http://docs.python.org/library/logging.html) module. You can print the log in a separate thread that the one which read network. Think to make your code reusable for other threads, for the next time ;). – Alexis Huet Aug 09 '12 at 10:17
  • 1
    @sHoM: signals such as SIGINT are received by a *main* thread in Python so if the code in your question is not executed in the main thread then it never receives `KeyboardInterrupt`. – jfs Aug 09 '12 at 11:05