How to prevent termination of a running program using “ctrl+c” in Linux using python?

自古美人都是妖i 提交于 2019-12-07 07:07:21

问题


I have written a piece of code in python, in which I am asking questions and users should give their input. Sometimes, these questions are difficult for the user to understand(they are non-english). So most of the time they want to copy paste the sentence into google translate. However, since this code is running in the command prompt,they have to select the text and using "right click --> copy" they can copy the text into google translate. Sometimes, by mistake the press "ctrl+c"(it is natural for everyone to use this combination for copying). Doing this will terminate the code, and they have to start over. I need to know I can prevent this from happening. In other words, if they press "ctrl+c" nothing happens and my software doesn't abort. thanks


回答1:


import signal
def SigIntHand(SIG, FRM):
    print("Please Right click-copy. Ctrl-C does not work on the cmd prompt")

signal.signal(signal.SIGINT, SigIntHand)

or if you want it completely ignored:

import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)



回答2:


When you hit ctrl+c it sends SIGINT to the running process. You can catch it as described here.

You can find more about the different types of signals here.




回答3:


If using X, the text is normally copied to the clipboard once it's selected. Just paste it using middle mouse button or Shift+insert.



来源:https://stackoverflow.com/questions/6019192/how-to-prevent-termination-of-a-running-program-using-ctrlc-in-linux-using-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!