0

I wrote a script which has two methods one which collects logs and other method which does some operation on the logs collected, so my methods which collects logs is in a while loop and will wait for user to press CTRL+C. As soon as CTRL+C is detected it should start executing another method which does some operation on logs collected.

How do i implement CTRL+C; as detected it should start running another method.

s. hussain
  • 13
  • 1
  • You might want this : https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python Idk if i should flag this as duplicate tho – Nenri Nov 11 '19 at 16:19

2 Answers2

0

Just catch the KeyboardInterrupt exception:


try:
    method1()
except KeyboardInterrupt:
    method2()
ababak
  • 1,685
  • 1
  • 11
  • 23
  • This doesn't work in python console tho, but for scripts it's fine – Nenri Nov 11 '19 at 16:25
  • Works fine for me – ababak Nov 11 '19 at 16:28
  • @ababak will this be supported in ubuntu system, if i run the script in terminal – s. hussain Nov 11 '19 at 16:30
  • it works in a script but not in python console as i said (as a reminder, python console is when you run `python` or `python3` command alone) – Nenri Nov 11 '19 at 16:31
  • @Nenri just tried in Python console 2.7 and 3.6.8, it works fine – ababak Nov 11 '19 at 16:33
  • [Ubuntu (Python 3.6.8)](https://puu.sh/EDjrK/4bf89b9c9e.png) [Windows (Python 3.7.3)](https://puu.sh/EDjsc/27fd020793.png) – Nenri Nov 11 '19 at 16:33
  • Can you show the code with which you try ? i'm curious (I just tried on my Ubuntu with 2.7.15 and it doesn't work either) – Nenri Nov 11 '19 at 16:36
  • https://previews.dropbox.com/p/thumb/AAlFMP00UApWZwOQmPodrfzmld_iHTkM2BRt4X4HHqhnVkgIr-2WgeM25KEeI0-R7DCH4Ilz1cHfzHJU_He1iLLO0ROXnSoEGtog9BXSUnUg8T8Hx6q_fClhepNWfxGRbpKciXlkkBjkk8sJzHgr-itJDl6Zo_oKIXQvifgANVagbJXDGPuQIecsbgkIaO6G2vYm3iu3a-JqRj3QET65oUDLpjy7TbSxQUl6aFkCdmSYOeqvHYA96E29mdxK5xVV71WrQVB831ve20GBYA5d7LlHOjXNGUErnKpdYzbFr2roo6U1c26ScUk2xp5AysBQC6QHzmJJNoQANncQRWlO8-Io/p.png – ababak Nov 11 '19 at 16:37
  • Tried it on Windows and got the same result as on your screenshots. But if you enclose the loop inside the try/except, it works fine. – ababak Nov 11 '19 at 16:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202157/discussion-between-ababak-and-nenri). – ababak Nov 11 '19 at 16:46
  • @s.hussain I am glad it worked, then you may accept my answer :) – ababak Nov 12 '19 at 08:30
  • @s.hussain you forgot to accept or at least upvote the answer if it did help you. – ababak Nov 26 '19 at 10:08
-1

Use the Try/Except as follows:

try:
    foo() --> #execute the first method
except KeyboardInterrupt:
    foo2() --> #execute the second method when CTRL + C pressed.
EddyIT
  • 133
  • 6