[英]Python: cmd execute last command while prompt and empty line
问题可能不够清楚得到。
让我详细说清楚。 我正在使用 python cmd 库来实现我自己的 CLI 框架,当点击 Enter 按钮而不输入任何命令时,它会执行最后一个命令。 这不是我想做的。
mycli~: cmd --args
executes command
execution stops
mycli~:[hit enter button]
然后它会再次执行 cmd --args。 但是我只想用新的线下去。
def emptyline(self):
pass
会做的很好!
经过长时间的谷歌搜索,我找不到一个有价值的建议来防止这种情况。 我决定进入 cmd 库并覆盖该方法。
我发现 cmd 依次执行precmd 、 onecmd和postcmd方法。 我跟踪了代码,发现 onecmd 是执行给定行的主要代码。 它检查解析然后检查行。 如果 line 为空,则调用 emptyline 方法并返回最后一个命令,该命令是一个名为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:
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')
这可能没什么大不了的,但请记住这一点以防万一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.