10

我正在使用cmdPython 中的模块来构建一个小的交互式命令行程序。但是,从这个文档:http : //docs.python.org/2/library/cmd.html,不清楚什么是以编程方式退出程序(即cmdloop)的干净方式。

理想情况下,我想exit在提示符下发出一些命令,然后退出程序。

4

2 回答 2

15

您需要覆盖该postcmd方法:

Cmd.postcmd(停止,行)

在命令调度完成后执行的钩子方法。这个方法是 Cmd 中的一个存根;它的存在是为了被子类覆盖。line 是执行的命令行,stop 是一个标志,指示调用 postcmd() 后是否终止执行;这将是 onecmd() 方法的返回值。该方法的返回值将作为stop对应的内部标志的新值;返回 false 将导致解释继续。

cmdloop文档中:

当 postcmd() 方法返回真值时,此方法将返回。postcmd() 的 stop 参数是命令对应的 do_*() 方法的返回值。

换句话说:

import cmd
class Test(cmd.Cmd):
    # your stuff (do_XXX methods should return nothing or False)
    def do_exit(self,*args):
        return True
于 2013-03-21T01:20:44.760 回答
0

另一个解决方案是简单地引发并捕获自定义异常。

import cmd

class ExitCmdException(Exception):
    pass #Could do something but just make a simple exception

class myCmd(cmd.Cmd):
    #...
    def do_quit(self, args):
        """ Quits the command loop """
        raise ExitCmdException()

#...
try:
    foo.cmdloop()
except ExitCmdException as e:
    print('Good Bye')

于 2021-05-11T18:42:18.770 回答