我试图用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
您可以将键盘中断定义为异常:
我已经写了一个你想要的工作版本。您应该重写}类的方法。在
cmdloop
和{我为
cmdloop
方法中的键盘中断处理定义了一个新关键字:我在
^{pr2}$onecmd
方法中处理了这个关键字。如果line
变量包含此关键字,则该方法将向STDOUT写入一个\n
并返回。在您可以在下面看到完整的代码工作代码:
输出:
希望你能帮我解决问题。在
相关问题 更多 >
编程相关推荐