如何用Python命令sh捕获ctrl+c

2024-09-28 13:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python创建一个shell,使用cmd包。我想重现一个“真正的”shell(bash,csh,…)的行为,也就是说,当你输入一个命令时,你意识到你所做的是错误的,你用ctrl+c来获得一个新的干净的提示。在

我试图捕捉SIGINT,然后调用一个只返回的方法,但它什么也不做。在

下面是一个示例:

#! /usr/bin/python
# -*- coding: utf-8 -*-

from cmd import Cmd
import signal
import sys


class myPrompt(Cmd):

  def do_exit(self, inp):
    """
         Exit the shell
    """
    return True

  def do_test(self):
    print "hello"
    return


p=myPrompt()

def signal_handler(sig, frame):
  print "world"
  p.do_test()
  return

signal.signal(signal.SIGINT, signal_handler)

p.cmdloop()


编辑:

我按照彼得·伍德的建议修改了我的代码:

^{pr2}$

我得到了这个错误:

(Cmd) Traceback (most recent call last):
  File "./test2.py", line 41, in <module>
    p.cmdloop()
  File "/usr/lib/python2.7/cmd.py", line 130, in cmdloop
    line = raw_input(self.prompt)
KeyboardInterrupt

Tags: importselfcmdsignalreturnusrdef错误
2条回答

您可以将键盘中断定义为异常:

try:
    your_code()
except KeyboardInterrupt:
    abort_code()

我已经写了一个你想要的工作版本。您应该重写cmdloop和{}类的方法。在

我为cmdloop方法中的键盘中断处理定义了一个新关键字:

if self.use_rawinput:
    try:
        line = input(self.prompt)
    except EOFError:
        line = "EOF"
    except KeyboardInterrupt:
        line = "ctrl_c"  # You can handle the `KeyboardInterrupt` exception through this keyword.

我在onecmd方法中处理了这个关键字。如果line变量包含此关键字,则该方法将向STDOUT写入一个\n并返回。在

^{pr2}$

您可以在下面看到完整的代码工作代码:

#! /usr/bin/python
# -*- coding: utf-8 -*-

from cmd import Cmd


class MyPrompt(Cmd):

    @staticmethod
    def do_exit(*args):
        return True

    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline

                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = input(self.prompt)
                        except EOFError:
                            line = "EOF"
                        except KeyboardInterrupt:
                            line = "ctrl_c"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline

                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass

    def onecmd(self, line):
        """Interpret the argument as though it had been typed in response
        to the prompt.

        This may be overridden, but should not normally need to be;
        see the precmd() and postcmd() methods for useful execution hooks.
        The return value is a flag indicating whether interpretation of
        commands by the interpreter should stop.

        """
        cmd, arg, line = self.parseline(line)
        if not line:
            return self.emptyline()
        if cmd is None:
            return self.default(line)
        self.lastcmd = line
        if line == "EOF":
            self.lastcmd = ""
        if line == "ctrl_c":
            self.stdout.write("\n")
            return
        if cmd == "":
            return self.default(line)
        else:
            try:
                func = getattr(self, "do_" + cmd)
            except AttributeError:
                return self.default(line)
            return func(arg)


p = MyPrompt()
p.cmdloop()

输出:

python3 test_cmd.py 
(Cmd) test
*** Unknown syntax: test
(Cmd) test1
*** Unknown syntax: test1
(Cmd) test2  <  Ctrl+C has been pushed and I got a new empty prompt
(Cmd) test3  <  Ctrl+C has been pushed and I got a new empty prompt
(Cmd)   <  I got a new empty prompt

希望你能帮我解决问题。在

相关问题 更多 >

    热门问题