2013-05-10 40 views
9

这个问题可能不够清楚得到。Python:cmd执行最后的命令,而提示和空行

让我清楚一点。我正在使用python cmd库来实现我自己的CLI框架,并且在不输入任何命令的情况下点击输入按钮时,它会执行最后一条命令。这不是我想要做的一件事。

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

然后它会再次执行cmd --args。不过,我只想用新的路线走下去。

回答

6

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

我计算出来的是CMD执行PRECMDonecmdPOSTCMD方法顺序。我追溯了代码,发现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') 

这可能不是一个大问题,但记住这一点,以防万一。

+3

+1自我回答对SO – msw 2013-05-10 10:11:37

+0

有好处,谢谢@msw我希望这会有所帮助。 – 2013-05-10 10:58:07

+0

谢谢你解决这个问题。我对cmd模块为此操作提供的默认行为感到困惑。 – oneself 2015-07-18 15:16:54

10
def emptyline(self): 
     pass 

会做得很好!

相关问题