Friday, March 4, 2011

[Level 2] Handle with ctrl+c, ctrl+d in python script

If you want to handle ctrl+c, ctrl+d in your python script,
you can catch KeyboardInterrupt and EOFError these two exception.
The sample code as the following:

#!/bin/env python
import os, sys

def disableCtrlD():
    os.popen("stty eof '^C^D'").read()

def enableCtrlD():
    os.popen("stty eof '^D'").read()

def testCD1():
    while True:
        try:
            a = ''
            a = raw_input('CLI(quit)> ')
            if a == 'quit':
                break
        except KeyboardInterrupt, e:
            print e
            print 'why you press ctrl+c'
        except EOFError, e:
            print e
            print 'why you press ctrl+d'
        except Exception, e:
            print e

def testCD2():
    disableCtrlD()
    while True:
        try:
            a = ''
            a = raw_input('CLI(quit)> ')
            if a == 'quit':
                break
        except KeyboardInterrupt, e:
            print e
            print 'why you press ctrl+c'
        except Exception, e:
            print e
    enableCtrlD()

if __name__ == '__main__':
    testCD1()
    testCD2()


Wish this helps.
regards,
Stanley Huang