如何防止用户通过 CTRL + 停止脚本Z?
我想阻止用户通过在 python 命令行解释器脚本中按 CTRL + Z 返回 shell 提示符。我怎样才能做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以为 SIGTSTP 编写一个信号处理程序,该信号处理程序由 Ctrl + Z 触发。这是一个例子:
You could write a signal handler for SIGTSTP, which is triggered by Ctrl + Z. Here is an example:
以下在我的 Linux 机器上实现了这个技巧:
这是一个完整的示例:
按照 @ZelluX 的建议安装我自己的信号处理程序在这里不起作用:按 Ctrl+Z while在
raw_input()
中给出了一个虚假的EOFError
:The following does the trick on my Linux box:
Here is a complete example:
Installing my own signal handler as suggested by @ZelluX does not work here: pressing Ctrl+Z while in
raw_input()
gives a spuriousEOFError
:粗略地说,在烘焙或规范模式下,来自 Unix/Linux 终端的 Ctrl+Z 将导致终端驱动程序向前台应用程序生成“挂起”信号。
所以你有两种不同的总体方法。更改终端设置或忽略该信号。
如果将终端置于“原始”模式,则禁用该信号生成。还可以使用终端设置(
import tty
并阅读有关 tcsetattr 的信息,还可以阅读“stty”和 terminfo(5) 的手册页以获取更多详细信息)。ZelluX 已经描述了最简单的信号处理方法。
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.
即使您捕获 Ctrl+Z (这取决于您的终端设置 - 请参阅 stty(1)),用户还可以通过其他方式返回命令行。防止返回 shell 的唯一“真正”方法是使用 exec 删除 shell 进程。因此,在用户的启动文件 (
.profile|.bash_profile|.cshrc
) 中执行以下操作:摆脱这种情况!
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:Get out of that!