【问题标题】:Is there a pattern for writing a python program that responds like a shell program是否有编写像 shell 程序一样响应的 python 程序的模式
【发布时间】:2018-04-09 20:29:44
【问题描述】:

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

是否有用于执行此操作的标准模式或库,还是我只使用 while True:stdin.readline() 之类的东西?

【问题讨论】:

标签: python python-3.x interactive-shell


【解决方案1】:

这就是标准库中的cmd module 的用途:

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

来自Example section

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!

【讨论】:

  • 太棒了。通过阅读 cmd 文档,这看起来完全符合我的需要。我不清楚如何在谷歌上搜索答案——我的正常做法——因为这些术语在不同的上下文中具有不同的含义。感谢非常有帮助的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 2021-10-27
相关资源
最近更新 更多