How to prevent user stopping script by CTRL + Z?

2019-06-02 10:45发布

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

4条回答
做个烂人
2楼-- · 2019-06-02 10:53

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 
查看更多
姐就是有狂的资本
3楼-- · 2019-06-02 11:03

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!

查看更多
看我几分像从前
4楼-- · 2019-06-02 11:06

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.

查看更多
神经病院院长
5楼-- · 2019-06-02 11:09

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
查看更多
登录 后发表回答