How to prevent user stopping script by CTRL + Z?

2019-06-02 10:27发布

问题:

I want to prevent user to go back to shell_prompt by pressing CTRL + Z from my python command line interpreter script.

回答1:

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 


回答2:

Roughly speaking the Ctrl+Z from a Unix/Linux terminal in cooked or canonical modes will cause the terminal driver to generate a "suspend" signal to the foreground application.

So you have two different overall approaches. Change the terminal settings or ignore the signal.

If you put the terminal into "raw" mode then you disable that signal generation. It's also possible to use terminal settings (import tty and read the info about tcsetattr, but also read the man pages for ``stty` and terminfo(5) for more details).

ZelluX has already described the simplest signal handling approach.



回答3:

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


回答4:

Even if you trap Ctrl+Z (which depends on your terminal settings - see stty(1)) then there are other ways the user can return to the command-line. The only 'real' way of preventing a return to the shell is to remove the shell process by using exec. So, in the user's startup file (.profile|.bash_profile|.cshrc) do:

exec python myscript.py

Get out of that!