簡體   English   中英

檢查通過 python cmd 模塊傳遞的參數

[英]Check argument passed via python cmd module

這是一個兩部分的問題,請參見下文:

  • 我需要創建某種控制台供測試人員手動運行一些命令! cmd模塊是一個好方法嗎?

下面是我到目前為止使用cmd模塊的代碼,我只是想學習,到目前為止我有兩個問題:

  • 為什么自動完成功能不起作用? 如果我雙擊<TAB>我什么也得不到,光標只是向前移動。 不是默認提供自動完成功能嗎?

  • 我是否必須為每種方法處理錯誤數量的參數? 如果使用錯誤數量的參數調用方法或何時應該使用參數調用它們而它們沒有調用,我希望方法-“幫助”文本自動顯示。

.

class InteractiveConsole(cmd.Cmd):
    """ Interactive command line """

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "=>> "
        self.intro = "Welcome to IRT console!"

    def do_hist(self, args):
        """Print a list of commands that have been entered"""
        print self._hist

    def do_exit(self, args):
        """Exits from the console"""
        return -1

    def do_help(self, args):
        """Get help on commands
           'help' or '?' with no arguments prints a list of commands for which help is available
           'help <command>' or '? <command>' gives help on <command>
        """
        # # The only reason to define this method is for the help text in the doc string
        cmd.Cmd.do_help(self, args)

    # # Override methods in Cmd object ##
    def preloop(self):
        """Initialization before prompting user for commands.
           Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
        """
        cmd.Cmd.preloop(self)  # # sets up command completion
        self._hist = []  # # No history yet
        self._locals = {}  # # Initialize execution namespace for user
        self._globals = {}

    def postloop(self):
        """Take care of any unfinished business.
           Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
        """
        cmd.Cmd.postloop(self)  # # Clean up command completion
        print "Exiting..."

    def precmd(self, line):
        """ This method is called after the line has been input but before
            it has been interpreted. If you want to modify the input line
            before execution (for example, variable substitution) do it here.
        """
        if line != '':
            self._hist += [ line.strip() ]
        return line

    def postcmd(self, stop, line):
        """If you want to stop the console, return something that evaluates to true.
           If you want to do some post command processing, do it here.
        """
        return stop

    def default(self, line):
        """Called on an input line when the command prefix is not recognized.
           In that case we execute the line as Python code.
        """
        try:
            exec(line) in self._locals, self._globals
        except Exception, e:
            print e.__class__, ":", e

    def emptyline(self):
        """Do nothing on empty input line"""
        pass





    def do_install(self, pathToBuild):
        """install [pathToBuild]
        install using the specified file"""
        if pathToBuild:
            print "installing %s" % pathToBuild
        else:
            print "<ERROR> You must specify the absolute path to a file which should be used!"


    def do_configure(self, pathToConfiguration):
        """configure [pathToConfiguration]
        configure using the specified file"""
        if pathToConfiguration:
            print "configuring %s" % pathToConfiguration
        else:
            print "<ERROR> You must specify the absolute path to a file which should be used!"

cmd文檔

可選參數completekey是完成鍵的readline名稱; 它默認為Tab 如果completekey不是None並且readline可用,則命令完成將自動完成。

您需要有readline可用於選項卡完成才能工作。

命令方法只接受一個參數,您需要在命令方法本身中解析參數。 當然,如果需要,您可以調用self.do_help()self.help_<cmd>()方法。

對於第一部分,是的,我發現 cmd 模塊易於使用且功能強大,足以實現類似於 Python 內置命令提示符的 CLI。

對於第二部分的第一個問題,您需要通過實現像 complete_install(self, word, line, begindex, endindex) 這樣的方法來告訴模塊如何完成命令行,該方法獲取當前單詞、行、開始和結束索引在行中,並返回表示有效完成的字符串列表或元組。 您應該通常根據當前單詞(第一個參數)計算和過濾列表。

例如,我使用一個命令“ll”來設置日志記錄級別,實現如下:

def complete_ll(self, a, ln, bi, ei):
    return tuple(
        k for k in logging._nameToLevel.keys()
        if k.casefold().find(a.casefold()) >= 0)

def do_ll(self, a):
    "Set or get debug level: DL [10 .. 50 | levelName]"
    def ll():
        n = log.getEffectiveLevel()
        return f"{logging.getLevelName(n)} ({n})"
    print(ll())
    if a:
        try:
            log.setLevel(eval(a.upper(), logging._nameToLevel))
            print("Logging level changed to", ll())
        except Exception as e:
            log.exception(f"{e}, value {a}", exc_info=1)

對於第二個問題,是的,您應該檢查“do_...”方法中參數的數量、類型和有效性,這在您的示例中已在某種程度上完成。 當然,您也可以在那時調用“help_...”方法,如果它真的有幫助的話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM