gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:29:25 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com