Skip to content

创建命令行程序的模板

custom_shell.py

python
import re
import sys

class IshmaelShell:
    def __init__(self):
        self.delimiter = ">"
        self.command_patterns = {
            "^ls$": self.list_files,
            "^cat\s(.+)$": self.read_file,
            "^exit$": self.exit_shell
        }
    
    def run(self):
        while True:
            user_input = input(f"{self.delimiter} ")
            for pattern, func in self.command_patterns.items():
                match = re.match(pattern, user_input)
                if match:
                    args = match.groups()
                    func(*args)

    def list_files(self):
        # implementation of list_files

    def read_file(self, file_path):
        # implementation of read_file

    def exit_shell(self):
        sys.exit()

def main():
    shell = IshmaelShell()
    shell.run()

if __name__ == "__main__":
    main()

Released under the MIT License.