Run a function after keyboard interrupt in python

0 votes
def print_data():
    print("print keyboardinterrupt")
    try:
        while True:
            print(1)
    except KeyboardInterrupt:
        print_data()
    exit()

I want the output as the print statement in the print_data function when I press ctrl+F2 in pycharm. I am using pycharm 2018.3 version and python 2.7.16 version.

Jul 26, 2019 in Python by Karan
15,116 views

1 answer to this question.

0 votes

Below is the code to run a function when keyboard interruption occurs.

import signal


print("press ctrl+c for interruption") 


def xyz():

    print("im xyz")

  

def keyboardInterruptHandler(signal, frame):

    xyz()

    #print("call your function here".format(signal))

    exit(0)

signal.signal(signal.SIGINT, keyboardInterruptHandler)

while True:

    pass

Hope this helps!!

If you need to learn more about Python, It's recommended to join Python Online Training today.

Thanks!

answered Jul 26, 2019 by Shri

Related Questions In Python

0 votes
1 answer

Is it possible to run a function in Python using the command line?

Suppose your file name is demo.py and ...READ MORE

answered Jun 26, 2019 in Python by Neel
• 3,020 points
1,071 views
0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
1,185 views
0 votes
1 answer

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here ...READ MORE

answered Sep 19, 2018 in Python by Priyaj
• 58,020 points
1,160 views
0 votes
1 answer

What does calling a function means in Python?

Calling a function means that you are ...READ MORE

answered Dec 18, 2018 in Python by Shuvodip
1,067 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,467 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,127 views
0 votes
1 answer

Edit a function in Python IDLE

No, if you have readline support enabled, ...READ MORE

answered Jul 23, 2019 in Python by SDeb
• 13,300 points
2,091 views
0 votes
1 answer

How do you make a higher order function in Python?

You have two choices to create higher-order ...READ MORE

answered Jul 25, 2019 in Python by Yesha
1,157 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP