-1

我想修改我编写的 python 程序以接受来自命令行的命令,然后像 shell 一样响应这些命令。

是否有这样做的标准模式或库,或者我只是使用类似 awhile True:和的东西stdin.readline()

4

1 回答 1

2

这就是标准库中的cmd模块的设计目的:

该类Cmd为编写面向行的命令解释器提供了一个简单的框架。这些通常对测试工具、管理工具和原型很有用,这些原型稍后将被包装在更复杂的界面中。

并从示例部分

cmd模块主要用于构建允许用户以交互方式使用程序的自定义 shell。

和一个快速演示示例:

import cmd

class CmdDemo(cmd.Cmd):
    intro = "Welcome to the cmd module demo. Type any command, as long as it's black!"
    prompt = '(demo) '

    def default(self, arg):
        print("Sorry, we do't have that color")

    def do_black(self, arg):
        """The one and only valid command"""
        print("Like Henry Ford said, you can have any color you like.")
        print(f"You now have a black {arg}")

    def do_exit(self, arg):
        """Exit the shell"""
        print('Goodbye!')
        return True

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

运行时会产生:

Welcome to the cmd module demo. Type any command, as long as it's black!
(demo) ?

Documented commands (type help <topic>):
========================================
black  exit  help

(demo) help black
The one and only valid command
(demo) red Volvo
Sorry, we do't have that color
(demo) black Austin Martin
Like Henry Ford said, you can have any color you like.
You now have a black Austin Martin
(demo) exit
Goodbye!
于 2018-04-09T20:34:08.803 回答