Python:cmd在提示和空行时执行最后一个命令
这个问题可能不够清楚,无法理解 让我详细说明一下。我使用pythoncmd库来实现我自己的CLI框架,当点击enter按钮而不键入任何命令时,它会执行最后一个命令。这不是我想做的Python:cmd在提示和空行时执行最后一个命令,python,cmd,command-line-interface,Python,Cmd,Command Line Interface,这个问题可能不够清楚,无法理解 让我详细说明一下。我使用pythoncmd库来实现我自己的CLI框架,当点击enter按钮而不键入任何命令时,它会执行最后一个命令。这不是我想做的 mycli~: cmd --args executes command execution stops mycli~:[hit enter button] 然后它将再次执行cmd--args。然而,我只想继续使用新的产品线。在长时间的谷歌搜索之后,我找不到有价值的建议来防止这种情况。我决定进入cmd库并重写该方法 我
mycli~: cmd --args
executes command
execution stops
mycli~:[hit enter button]
然后它将再次执行cmd--args。然而,我只想继续使用新的产品线。在长时间的谷歌搜索之后,我找不到有价值的建议来防止这种情况。我决定进入cmd库并重写该方法 我发现cmd依次执行precmd、onecmd和postmd方法。我跟踪了代码,发现onecmd是执行给定行的主要命令。它检查解析,然后检查行。如果line为空,则调用emptyline方法并返回最后一个命令,该命令是一个名为lastcmd的全局变量。我重写了emptyline方法,然后我的问题得到了解决 这是我写的方法
def emptyline(self):
"""Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty
command entered.
"""
if self.lastcmd:
return self.onecmd(self.lastcmd)
这是我的:
def emptyline(self):
"""Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty
command entered.
"""
if self.lastcmd:
self.lastcmd = ""
return self.onecmd('\n')
这可能没什么大不了的,但请记住这一点,以防万一
def emptyline(self):
pass
那就好了 谢谢你弄明白了。我对cmd模块为这个操作提供的默认行为感到困惑。似乎第一个答案也是如此,代码更少。这不是答案吗?这个问题我花了一段时间才弄明白