我正在使用 Python 中的 cmd
模块构建一个小型交互式命令行程序。然而,从这个文件:http://docs.python.org/2/library/cmd.html ,不清楚以编程方式退出程序(即 cmdloop)的干净方法是什么。
理想情况下,我想在提示符下发出一些命令 exit
,这将退出程序。
最佳答案
您需要重写postcmd
方法:
Cmd.postcmd(stop, line)
Hook method executed just after a command dispatch is finished. This method is a stub in Cmd; it exists to be overridden by subclasses. line is the command line which was executed, and stop is a flag which indicates whether execution will be terminated after the call to postcmd(); this will be the return value of the onecmd() method. The return value of this method will be used as the new value for the internal flag which corresponds to stop; returning false will cause interpretation to continue.
来自 cmdloop
文档:
This method will return when the postcmd() method returns a true value. The stop argument to postcmd() is the return value from the command’s corresponding do_*() method.
换句话说:
import cmd
class Test(cmd.Cmd):
# your stuff (do_XXX methods should return nothing or False)
def do_exit(self,*args):
return True
关于python - 如何干净地退出cmd模块的cmd循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537427/