溫馨提示×

python cmd庫如何實現交互

小樊
112
2024-12-05 14:05:35
欄目: 編程語言

cmd庫是一個Python庫,用于創建一個簡單的命令行界面(CLI)。要實現交互,你可以使用cmd.Cmd類,并在其中定義一些命令和命令處理函數。下面是一個簡單的示例:

import cmd

class MyCLI(cmd.Cmd):
    prompt = 'mycli> '

    def do_hello(self, arg):
        """Say hello to the user."""
        print(f'Hello, {arg}')

    def do_greet(self, arg):
        """Greet the user with their name."""
        name = arg or 'stranger'
        print(f'Hello, {name}!')

    def do_exit(self, arg):
        """Exit the application."""
        print('Bye!')
        return True

if __name__ == '__main__':
    MyCLI().cmdloop()

在這個示例中,我們定義了一個名為MyCLI的類,它繼承自cmd.Cmd。我們設置了命令提示符為mycli> ,并定義了三個命令:hello、greetexit。每個命令都有一個與之關聯的處理函數,例如do_hello、do_greetdo_exit。

當用戶輸入命令時,cmdloop()方法會處理輸入的命令并調用相應的處理函數。例如,如果用戶輸入hello Alice,則會調用do_hello函數并打印Hello, Alice。如果用戶輸入exit,則會調用do_exit函數并退出應用程序。

你可以根據需要添加更多的命令和處理函數,以實現更復雜的交互功能。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女