是否有编写响应类似于 shell 程序的 python 程序的模式
Is there a pattern for writing a python program that responds like a shell program
我想修改我编写的 python 程序以接受来自命令行的命令,然后像 shell 一样响应这些命令。
是否有标准模式或库来执行此操作,或者我只是使用 while True:
和 stdin.readline()
之类的东西?
这就是标准库中 cmd
module 的用途:
The Cmd
class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.
和来自 Example section:
The cmd
module is mainly useful for building custom shells that let a user work with a program interactively.
和一个快速演示示例:
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!
我想修改我编写的 python 程序以接受来自命令行的命令,然后像 shell 一样响应这些命令。
是否有标准模式或库来执行此操作,或者我只是使用 while True:
和 stdin.readline()
之类的东西?
这就是标准库中 cmd
module 的用途:
The
Cmd
class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.
和来自 Example section:
The
cmd
module is mainly useful for building custom shells that let a user work with a program interactively.
和一个快速演示示例:
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!