Python:在提示符下出现空白行时,cmd执行最后一个命令 [英] Python: cmd execute last command while prompt and empty line

查看:172
本文介绍了Python:在提示符下出现空白行时,cmd执行最后一个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能还不够清楚。

The question may be not clear enough to get.

请让我详细说明。我正在使用python cmd库实施自己的CLI框架,并且在不按任何输入命令的情况下按Enter键时,它会执行最后一个命令。

Let me clear in details. I'm using python cmd library to implement my own CLI framework and when hit the enter button without typing any command it executes last command. This it not one I wanna do.

mycli~: cmd --args
executes command
execution stops
mycli~:[hit enter button]

然后它将再次执行cmd- args。但是,我只是想换行。

Then it will execute again cmd --args. However I just want to go down with new line.

推荐答案

经过长时间的搜寻后,我找不到防止这种情况的有价值的建议。我决定进入cmd库并重写该方法。

After a long googling I could not find a valuable advise to prevent this. I decide to go inside the cmd library and override the method.

我发现cmd执行 precmd onecmd postcmd 方法。我跟踪了代码,发现onecmd是执行给定行的主要命令。它检查解析,然后检查行。如果line为空,它将调用emptyline方法,并返回最后一个命令,该命令是名为 lastcmd 的全局变量。我重写了emptyline方法,然后问题解决了。

I figured it out that cmd execute precmd, onecmd and postcmd methods sequentially. I traced the code and see that onecmd is the main one which exetues the given line. It checks parses then check the line. If line is empty it calls the emptyline method and it returns the last command which is a global variable called as lastcmd. I override the emptyline method then my issue got fixed.

这里是我编写的方法。

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')

这可能没什么大不了的,但请记住以防万一。

It might not be a big deal but keep that in mind just in case.

这篇关于Python:在提示符下出现空白行时,cmd执行最后一个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆