Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user stopping script by CTRL + Z?

I want to prevent the user from going back to the shell prompt by pressing CTRL + Z from my python command line interpreter script. How can I do that?

like image 958
shahjapan Avatar asked Dec 01 '22 06:12

shahjapan


2 Answers

You could write a signal handler for SIGTSTP, which is triggered by Ctrl + Z. Here is an example:

import signal

def handler(signum, frame):
    print 'Ctrl+Z pressed, but ignored'

signal.signal(signal.SIGTSTP, handler)

while True:
   pass 
like image 58
ZelluX Avatar answered Dec 05 '22 19:12

ZelluX


The following does the trick on my Linux box:

signal.signal(signal.SIGTSTP, signal.SIG_IGN)

Here is a complete example:

import signal

signal.signal(signal.SIGTSTP, signal.SIG_IGN)

for i in xrange(10):
  print raw_input()

Installing my own signal handler as suggested by @ZelluX does not work here: pressing Ctrl+Z while in raw_input() gives a spurious EOFError:

aix@aix:~$ python test.py
^ZCtrl+Z pressed, but ignored
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    raw_input()
EOFError
like image 37
NPE Avatar answered Dec 05 '22 20:12

NPE