python - 如何干净地退出cmd模块的cmd循环

标签 python cmd

我正在使用 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/

相关文章:

batch-file - 如何添加右键单击选项以使用所选文件的名称搜索网络?

python - Django - 每个域的 URLConf?

python - 根据指定的索引对数据框进行排序

python - 连接 2 modbus slave pymodbus 时出错

java - 完全使用 Java 重定向 CMD.exe 进程的输入/输出/错误流

在 R 中使用 shell() 运行 .bat 文件

web - 如何为代码实验室配置 Firebase SDK?

python - 将逗号分隔的 .txt 文件转换为字典

python - 数据库查询结果作为 Django 模型字段的默认值?

batch-file - 删除批处理文件中具有特定扩展名的文件