How to prevent user stopping script by CTRL + Z?

徘徊边缘 提交于 2019-12-22 20:12:08

问题


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:


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



回答3:


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.




回答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!



来源:https://stackoverflow.com/questions/9174799/how-to-prevent-user-stopping-script-by-ctrl-z

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